解释它的最好方法是准确显示我想要实现的目标:
案例1:"search for fenway park in boston"
提取:组1 - >
"fenway park",组2 - >"boston"
案例2:"search for fenway park"
提取:组1 - >"fenway
park"
请注意,在这两种情况下,我希望能够针对变化"search"("look for","find"以及,等...) ("in","at","around"等...).
我尝试了很多不同的变体,但最终都是"fenway park in boston"在第1组中提取而在第2组中没有任何内容,或者如果我得到第1个案例,则案例2将无效.
这应该适合你
^(?:search for|look for|find)\s*(.*?)(?:\s*(?:in|around|at)\s*(.*))?$
Run Code Online (Sandbox Code Playgroud)
您可以添加更多子句,例如look for/in/at向非捕获组添加moer 或子句.
说明:
@"
^ # Assert position at the beginning of a line (at beginning of the string or after a line break character)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
search\ for # Match the characters “search for” literally
| # Or match regular expression number 2 below (attempting the next alternative only if this one fails)
look\ for # Match the characters “look for” literally
| # Or match regular expression number 3 below (the entire group fails if this one fails to match)
find # Match the characters “find” literally
)
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 1
. # Match any single character that is not a line break character
*? # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
(?: # Match the regular expression below
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
in # Match the characters “in” literally
| # Or match regular expression number 2 below (attempting the next alternative only if this one fails)
around # Match the characters “around” literally
| # Or match regular expression number 3 below (the entire group fails if this one fails to match)
at # Match the characters “at” literally
)
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 2
. # Match any single character that is not a line break character
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
$ # Assert position at the end of a line (at the end of the string or before a line break character)
"
Run Code Online (Sandbox Code Playgroud)