正则表达式提取单词前后的数字

时间:2018-11-14 01:13:47

标签: regex stata

我有10000说明,我想使用正则表达式提取与短语``arrested''相关的数字。

例如:

"police arrests 4 people"
"7 people were arrested". 

数字范围为1-99

我尝试了以下代码:

gen arrest= regexm(description, "(^[1-9][0-9]$)[ ]*(arrests|arrested)")

我不能只提取数字,因为描述中还提到了与逮捕无关的数字。

3 个答案:

答案 0 :(得分:2)

以下对我有用(基于@PoulBak想法的解决方案):

clear

input strL var1
"This is 1 long string saying that police arrests 4 people"
"3 news outlets today reported that 7 people were arrested"
"several witnesses saw 5 people arrested and other 3 killed"
end

generate var2 = ustrregexs(0) if ustrregexm(var1, "(?:([1-9]?[0-9])[a-zA-Z ]{0,20}(?:arrests|arrested))|(?:(?:arrests|arrested)[a-zA-Z ]{0,20}([1-9]?[0-9]))")

list

   +-------------------------------------------------------------------------------------+
   |                                                       var1                     var2 |
   |-------------------------------------------------------------------------------------|
1. |  This is 1 long string saying that police arrests 4 people                arrests 4 |
2. |  3 news outlets today reported that 7 people were arrested   7 people were arrested |
3. | several witnesses saw 5 people arrested and other 3 killed        5 people arrested |
   +-------------------------------------------------------------------------------------+

答案 1 :(得分:1)

您可以使用此正则表达式:

(?:([1-9]?[0-9])[a-zA-Z ]{0,20}(?:arrests|arrested))|(?:(?:arrests|arrested)[a-zA-Z ]{0,20}([1-9]?[0-9]))

它将搜索按字母顺序分为2个,无论该数字是在“逮捕|被捕”之前还是之后。

它将创建一个非捕获Group,它与1-9中的number(可选)和0-9中的数字匹配。接下来是先匹配0 - 20 of any letter和空格(其他单词),然后再匹配'arrests OR arrested.,然后对相反的情况(数字在最后)进行或运算。

如果数字是“ within 20 chars”中的arrests|arrested,则匹配。

答案 2 :(得分:0)

也许是这样吗?

(\d+)[^,.\d\n]+?(?=arrest|custody)|(?<=arrest|custody)[^,.\d\n]+?(\d+)

Regex101

请记住,这与数字的文字版本不符(即,五个人被捕)-因此,如果需要,您必须将其合并。


打破常规

  • (\d+)[^,.\d\n]+?(?=arrest|custody)如果#在观看条款之前
    • (\d+)要捕获的数字,用+一个或多个数字
    • [^,.\d\n]+?匹配除逗号,,句点.,数字\d或换行符\n之外的所有内容。这些可防止FP使用不同的句子(必须包含在同一句子中)-+?一次或多次(懒惰)
    • (?=arrest|custody)积极向前看是否有两个词:
  • (?<=arrest|custody)[^,.\d\n]+?(\d+)如果#在观看条款之后
    • (?<=arrest|custody)积极回首,检查单词是否在#
    • 之前
    • [^,.\d\n]+?匹配除逗号,,句点.,数字\d或换行符\n之外的所有内容。这些可防止FP使用不同的句子(必须包含在同一句子中)-+?一次或多次(懒惰)
    • (\d+)要捕获的数字,用+一个或多个数字

其他注释

如果要添加数字的文字表示形式,则可以将其合并到(\d+)捕获组中。

如果除了被捕托管以外,还有其他需要注意的条款,可以将这些条款添加到两个环顾组

相关问题