简体   繁体   English

Javascript正则表达式以斜杠匹配单词

[英]Javascript regex to match word with slash

I'm trying to remove 2 char words and using this regex: 我试图删除2个字符,并使用此正则表达式:

/\b[\w\/]{2}\b/

given a string like: aa bb b/ 给定一个像这样的字符串: aa bb b/

http://regex101.com/r/dK6qF7/2 http://regex101.com/r/dK6qF7/2

Can anyone explain why 'b/' doesn't get matched and removed? 谁能解释为什么'b /'不被匹配和删除?

Thanks 谢谢

/ followed by the end of the string does not form a word boundary, so the last \\b is not satisfied. /后跟字符串的末尾不构成单词边界,因此不满足最后一个\\b If your engine can use lookbehinds, you can use: 如果您的引擎可以使用后向搜索,则可以使用:

(?<=[^\w\/]|^)[\w\/]{2}(?=[^\w\/]|$)

A word boundary will match if \\w is followed by \\W (ie [A-Za-Z0-9_] followed by [^A-Za-Z0-9_] ), or vice versa. 如果\\w后跟\\W (即[A-Za-Z0-9_]后接[^A-Za-Z0-9_] ),则单词边界匹配,反之亦然。

Using the regex \\bb/\\b and the input " b/ " , the first word boundary matches, since a space ( \\W ) is followed by b ( \\w ). 使用正则表达式\\bb/\\b和输入" b/ " ,第一个单词边界匹配,因为空格( \\W )后跟b\\w )。 But the second word boundary won't match: / ( \\W ) is followed by a space ( \\W ). 但是第二个单词的边界不匹配: /\\W )后跟一个空格( \\W )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM