繁体   English   中英

连续3个正则表达式,如果有的话

[英]regex for 3 consecutive words if there are any

我正在寻找正则表达式,如果有任何连续提取3个单词。 例如,如果我有2个字符串:

"1. Stack is great and awesome"
"2. Stack"

结果是:

"Stack is great"
"Stack" 

这个答案对我不起作用: 正则表达式:匹配3个连续的单词

我的努力:

(?:[A-ZŠČĆŽa-zščćž]+ )(?:[A-ZŠČĆŽa-zščćž]+ )(?:[A-ZŠČĆŽa-zščćž]+ )

你可以用

> x <- c("1. Stack is great and awesome", "2. Stack")
> regmatches(x, regexpr("[A-Za-z]+(?:\\s+[A-Za-z]+){0,2}", x))
[1] "Stack is great" "Stack"
## Or to support all Unicode letters
> y <- c("1. Stąck is great and awesome", "2. Stack")
> regmatches(y, regexpr("\\p{L}+(?:\\s+\\p{L}+){0,2}", y, perl=TRUE))
[1] "Stąck is great" "Stack"
## In some R environments, it makes sense to use another, TRE, regex:
> regmatches(y, regexpr("[[:alpha:]]+(?:[[:space:]]+[[:alpha:]]+){0,2}", x))
[1] "Stąck is great" "Stack"

查看正则表达式演示在线R演示以及替代正则表达式演示

请注意,正则表达式将从任何字符串中提取第一,第2或第3个字母单词。 如果您需要至少2个单词,请将{0,2}限制量词替换为{1,2}

要提取多个匹配项,请使用gregexpr而不是regexpr

图案细节

  • \\\\p{L}+ / [A-Za-z] - 任何1+ Unicode(如果使用[A-Za-z]则为ASCII)字母
  • (?:\\\\s+\\\\p{L}+){0,2} / (?:\\\\s+[a-zA-Z]+){0,2} - 0,1或2次连续出现:
    • \\\\s+ - 1+空格
    • \\\\p{L}+ / [A-Za-z] - 任何1+ Unicode(如果使用[A-Za-z]则为ASCII)字母

注意使用perl=TRUE参数和使用\\p{L}构造的正则表达式。 如果它不起作用,请尝试在模式的最开头添加(*UCP) PCRE动词,使所有通用/ Unicode /速记类真正识别Unicode。

请注意,所有这些正则stringr::str_extract都适用于stringr::str_extractstringr::str_extract_all

> str_extract(x, "\\p{L}+(?:\\s+\\p{L}+){0,2}")
[1] "Stack is great" "Stack"         
> str_extract(x, "[a-zA-Z]+(?:\\s+[a-zA-Z]+){0,2}")
[1] "Stack is great" "Stack"         
> str_extract(x, "[[:alpha:]]+(?:\\s+[[:alpha:]]+){0,2}")
[1] "Stack is great" "Stack" 

这里不支持(*UCP) ,因为stringr函数是ICU正则表达式,而不是PCRE。 Unicode测试:

> str_extract(y, "\\p{L}+(?:\\s+\\p{L}+){0,2}")
[1] "Stąck iç great" "Stack"         
> str_extract(y, "[[:alpha:]]+(?:\\s+[[:alpha:]]+){0,2}")
[1] "Stąck iç great" "Stack"         

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM