[英]Regex match “target string”
Environment: Visual Studio 2008 SP1 环境:Visual Studio 2008 SP1
How can I write the following regex? 我怎么写下面的正则表达式?
I'm trying to get to 'target string . 我正试图去'目标字符串 。 The pattern is any string between [name]=' ' 模式是[name] =''之间的任何字符串
/*Input String*/
SET [blah] = 'AE', [blah] = 'A1A', [number] = 004 WHERE [name]='target string'
/*Current Regex*/
(?<=[?name]?=).*(?=\')
/*Current Results*/
'AE', [blah] = 'A1A', [number] = 004 WHERE [name]='target string
/*Desired Results*/
'target string
You need to escape your square-brackets, or else they'll be misinterpreted as creating a character class. 你需要转义方括号,否则它们会被误解为创建一个字符类。 That is, you need: 也就是说,你需要:
(?<=\[?name\]?=).*(?=\')
I'd also recommend changing .*
to the more explicit '[^']*
, just so you don't risk catching anything after the target string; 我还建议将.*
改为更明确的'[^']*
,这样你就不会冒险在目标字符串之后捕获任何东西; and Tim Pietzcker points out (in a now-deleted comment) that you can write '
instead of \\'
(near the end of the regex); Tim Pietzcker指出(在一个现已删除的评论中)你可以写'
而不是\\'
(接近正则表达式的末尾); so: 所以:
(?<=\[?name\]?=)'[^']*(?=')
Does this do it? 这样做吗?
(?<=\[name]=).*?(?=')
Or if the target string has to be returned without the leading ('): 或者如果必须在没有前导(')的情况下返回目标字符串:
(?<=\[name]=').*?(?=')
Note: I assume that the target string does not have escaped apostrophes (''). 注意:我假设目标字符串没有转义撇号('')。
EDIT: This does the trick with the escaped apostrophes: 编辑:这与转义的撇号有关:
(?<=\[name]=)(''|.)+?(?='([^']|$))
It will find " 'John''s pub
" in 它将找到“ 'John''s pub
”
SET [blah] = 'AE', [blah] = 'A1A', [number] = 004 WHERE [name]='John''s pub'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.