【问题标题】:Construct pattern that match if there is no punctuation between two characters in R stringr如果 R stringr 中的两个字符之间没有标点符号,则构造匹配的模式
【发布时间】:2020-05-15 09:58:32
【问题描述】:

我有几个人的文本和他们的演讲。我需要提取人们的姓名和他们的党员身份。问题是有些人不是党员,我希望他们被排除在外。

我正在使用的文本是按以下方式构造的:

string = 'Author A. B., party member X. Some text. Author G. H., party Y. Some text. Author K. L., somebody. Text that mentions party. Author R. H., party X. Some text.'

我想要的结果是:

'Author A. B., party member X.' 
'Author G. H., party Y.'
'Author R. H., party X.'

我用过

str_extract_all(string, '[A-Z]\\w{1,50}\\s[A-Z]\\.\\s[A-Z]\\.,\\s(.*?)party(.*?)\\.')

作为模式请求,它运行良好,但它也匹配 Author K. L., somebody. Text that mentions party. 并且应该被排除。我试图实现异常标记[^\\.] 并匹配[A-Z]\\w{1,50}\\s[A-Z]\\.\\s[A-Z]\\.,\\s(.*?)[^\\.](.*?)party(.*?)\\.,但给出了扭曲的结果。

如果作者姓名和单词party 之间没有点,我需要找到匹配项。如果 - 之间有一个点,则不应匹配。有人可以帮我解决这个问题吗?

【问题讨论】:

标签: r regex stringr


【解决方案1】:

你可以使用

\b[A-Z]\w{1,50}\s[A-Z]\.\s*[A-Z]\.,[^.]*party[^.]*\.
\b[A-Z]\w{1,50}\s[A-Z]\.\s*[A-Z]\.,[\w\s]*party[^.]*\.

在代码中:

str_extract_all(string, '\\b[A-Z]\\w{1,50}\\s[A-Z]\\.\\s*[A-Z]\\.,[^.]*party[^.]*\\.')
str_extract_all(string, '\\b[A-Z]\\w{1,50}\\s[A-Z]\\.\\s*[A-Z]\\.,[\\w\\s]*party[^.]*\\.')

请参阅regex demo

详情

  • \b - 字边界
  • [A-Z] - 大写 ASCII 字母(使用 \p{Lu} 匹配任何 Unicode 大写字母)
  • \w{1,50} - 1 到 50 个字母、数字或 _
  • \s - 一个空格
  • [A-Z] - 一个大写的 ASCII 字母
  • \. - 一个点
  • \s*[A-Z]\. - 一个空格、一个大写的 ASCII 字母、一个点
  • , - 逗号
  • [^.]* - 除. 之外的 0 个或多个字符
  • [\w\s]* - 0 个或多个字母、数字、下划线或空格(除 _ 之外没有标点符号)
  • party - 一句话
  • [^.]*\. - 0 个或多个字符,而不是一个点和一个点。

【讨论】:

  • 哦,谢谢!它工作得很好。我在[] 中搞砸了点符号
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 2011-05-20
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
相关资源
最近更新 更多