5

我有一个形式为的字符串

Foo
"Foo"
"Some Foo"
"Some Foo and more"

我需要提取Foo引号中的值,并且可以被任意数量的字母数字和空格字符包围。因此,对于上面的示例,我希望输出为

<NoMatch>
Foo
Foo
Foo

我一直在努力让它发挥作用,这是迄今为止我使用前瞻/后向报价的模式。这适用于其他人,"Foo"但不适用于其他人。

(?<=")Foo(?=")

进一步扩大到

(?<=")(?<=.*?)Foo(?=.*?)(?=")

不起作用。

任何帮助将不胜感激!

4

4 回答 4

10

如果引号正确平衡并且引号字符串不跨越多行,那么您可以简单地在字符串中向前看以检查是否有偶数个引号。如果这不是真的,我们知道我们在一个带引号的字符串中:

Foo(?![^"\r\n]*(?:"[^"\r\n]*"[^"\r\n]*)*$)

解释:

Foo          # Match Foo
(?!          # only if the following can't be matched here:
 [^"\r\n]*   # Any number of characters except quotes or newlines
 (?:         # followed by
  "[^"\r\n]* # (a quote and any number of non-quotes/newlines
  "[^"\r\n]* # twice)
 )*          # any number of times.
 $           # End of the line
)            # End of lookahead assertion

regex101.com上实时查看

于 2013-05-24T11:07:54.200 回答
2

环视 ((?<=something)(?=something)) 不适用于可变长度模式,即 on .*。尝试这个:

(?<=")(.*?)(Foo)(.*?)(?=")

然后使用匹配字符串(取决于您的语言:$1,$2,...\1,\2,...某些数组的成员或类似的东西)。

于 2013-05-24T10:52:44.033 回答
0

在记事本++

search : ("[^"]*)Foo([^"]*")
replace : $1Bar$2
于 2013-05-24T11:09:18.987 回答
0

尝试用这种模式做一些事情:

"[^"]*?Foo[^"]*?"
于 2013-05-24T10:53:18.580 回答