0

有没有办法将一些字符串传递给正则表达式,而不用担心特殊字符的 ecranisation。

例如,我不会找到以单词“\north+west\”开头的行,因为你可以看到“\n”和“h+”应该被删除。那么问题是否有一些特殊的组合可以按原样编写文本?

/^\s+(<some special combination> \north+west\)\s+/i

或者也许你知道可以正确地整理我的文字的功能?

4

2 回答 2

1

In PHP and Perl you can use \Q...\E delimiters to autoescape metacharacters inside regexp. Quoting the doc:

\Q and \E can be used to ignore regexp metacharacters in the pattern. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

于 2013-04-12T15:13:45.217 回答
0

除了@raina77ow answer\Q...\E之外,当您通过 PHP 等需要模式分隔符的语言使用 pcre 时,如果您的字符串包含开始或结束分隔符,则无法使用该功能。例如,您不能编写如下模式:

/\Qabc/def\E/
~\Qabc~def\E~
[\Qabc[def\E]
[\Qabc]def\E]
(\Qabc)def\E)
(\Qabc(def\E)

唯一的方法是使用该preg_quote函数并将分隔符(仅当这个分隔符还不是特殊的正则表达式字符时)放在它的第二个参数中。

于 2013-04-12T14:46:43.543 回答