找到单个反斜杠后跟字母表

时间:2015-10-21 06:22:52

标签: javascript regex

我需要一个回归,找到所有单个反斜杠后跟一个字母。

所以我想找到像这样的模式中存在的反斜杠:

$email_header .= "Disposition-Notification-To: $from\r\n"; 
$email_header .= "X-Confirm-Reading-To: $from\r\n";

而不是这些模式:

\a
\f
\test

由于

1 个答案:

答案 0 :(得分:1)

已更新:

@Amadan在下面的评论中指出,JavaScript并没有实现lookbehind,这基本上打破了我的原始答案。

this stackoverflow post中提出的方法可能是解决此问题的合理途径。

基本上海报建议反转字符串并使用前瞻来匹配。如果我们这样做,那么我们希望匹配一串字母字符后跟一个反斜杠,但不会跟随多个反斜杠。正则表达式如下: /[a-zA-Z]+\\(?![\\]+)/g

[a-zA-Z]+ - match one or more alphabetic characters
\\        - followed by a single backslash
(?![\\]+) - not followed by one or more backslashes
g         - match it globally (more than one occurrence)

这种方法的缺点(除了必须反转你的字符串)是你不能只匹配反斜杠,但也必须匹配它之前的字母字符(因为JS没有lookbehind)

原始答案(使用lookbehind):

/(?<!\\)\\[a-zA-Z]+/g(使用negative lookbehind)将匹配单个反斜杠,后跟一个或多个字母,无论大小写如何。这个正则表达式分解如下:

(?<!\\)\\   - use negative lookbehind to match a \ that is not preceded by a \
[a-zA-Z]+   - match one or more letters of the alphabet, regardless of case
g           - match it globally

如果您只想匹配\而不是字母字符,则可以使用positive lookahead。正则表达式如下:/(?!>\\)\\(?=[a-zA-Z]+)/g并会像这样分解:

(?<!\\)\\     - use negative lookbehind to match a \ that is not preceded by a \
(?=[a-zA-Z]+) - and is followed by one or more alphabetic characters
g             - match it globally

如果您只希望正则表达式在行的开头匹配反斜杠,请在其前面添加^

您可以使用Rubular之类的工具来测试和播放正则表达式。

相关问题