改进我的正则表达式以包含包含小数和百分号的数字



我有以下正则表达式,它将捕获前 N 个单词并在下一个句点、感叹号或问号完成。 我需要获得单词数量不同的文本块,但我想要完整的句子。

regex = (?:w+[.?!]?s+){10}(?:w+,?s+)*?w+[.?!]

它适用于以下文本:

仅从虾壳中提取秸秆和壳聚糖的疗法 占2、4、6、8和10%发现提取秸秆8%是 在抑制藻类微囊藻属的生长方面非常有效。 细胞数量和叶绿素a的量在 治疗。这两个值持续下降,直到试验结束。

https://regex101.com/r/ardIQ7/5

但是,它不适用于以下文本:

仅从虾壳中提取秸秆和壳聚糖的疗法占 对于2、4、6、8和10%发现秸秆提取物8.2%高度 有效抑制藻类微囊藻属的生长。这 细胞数量和叶绿素A的量在以下过程中减少 治疗。这两个值持续下降,直到试验结束。

这是因为带有小数和%的数字(8.2%(。

我一直在试图弄清楚如何捕获这些项目,但需要一些帮助来为我指明正确的方向。我不只是想抓住第一句话。我想捕获 N 个单词,其中可能包含多个句子并返回完整的句子。

r = /
(?:           # begin a non-capture group
(?:           # begin a non-capture group
p{Alpha}+  # match one or more letters
|           # or
-?       # optionally match a minus sign
(?:       # begin non-capture group
d+     # match one or more digits
|         # or
d+     # match one or more digits
.      # match a decimal point
d+     # match one or more digits
)         # end non-capture group
%?        # optionally match a percentage character
)           # end non-capture group
[,;:.!?]?   # optionally ('?' following ']') match a punctuation char
[ ]+        # match one or more spaces      
)             # end non-capture group
{9,}?         # execute the preceding non-capture group at least 14 times, lazily ('?')
(?:           # begin a non-capture group
p{Alpha}+  # match one or more letters
|           # or
-?         # optionally match a minus sign
(?:       # begin non-capture group
d+     # match one or more digits
|         # or
d+     # match one or more digits
.      # match a decimal point
d+     # match one or more digits
)         # end non-capture group
%?          # optionally match a percentage character
)             # end non-capture group  
[.!?]         # match one of the three punctuation characters
(?!S)        # negative look-ahead: do not match a non-whitespace char
/x            # free-spacing regex definition mode

text等于您希望检查的段落("治疗提取稻草......审判结束》(

然后

text[r]
#=> "Therapy extract straw and chitosan from...the growth of algae Microcystis spp."

我们可以简化正则表达式的构造(并避免重复位(,如下所示。

def construct_regex(min_nbr_words)
common_bits = /(?:p{Alpha}+|-?(?:d+|d+.d+)%?)/
/(?:#{common_bits}[,;:.!?]? +){#{min_nbr_words},}?#{common_bits}[.!?](?!S)/
end

r = construct_regex(10)
#=> /(?:(?-mix:p{Alpha}+|-?(?:d+|d+.d+)%?)[,;:.!?]? +){10,}?(?-mix:p{Alpha}+|-?(?:d+|d+.d+)%?)[.!?](?!S)/

如果允许此正则表达式匹配无意义的单词,例如"ab2.3e%""2.3.2%".正如目前定义的那样,正则表达式将不匹配这些单词。

试试这个,(?:S+[,.?!]?s+){1,200}[sS]*?(. |!|?)

这将匹配 N 个字符。

如果第 N 个字符没有结束句子,那么它将匹配到上一个句子。N应该被提及为{1, N}

正则表达式

最新更新