简体   繁体   中英

javascript regex pattern to match words, with custom word boundary

I'm trying to match words in a string using regex in javascript.

Lets say the string is "I have c++ as a skill". I now want to count the number of occurrences of the "c++" substring. I do not want to match if the string is "I have c++test" or similar. So I need to check for word boundaries and include some special character like + and #.

I have the following code:

var str = "I have c++ as a skill, but I do not have c++test as a skill";

var regex = new RegExp("(?<![\\w+#])c\\+\\+(?![\\w+#])", "g");

count = (str.match(regex) || []).length; 

console.log(count); 

Expected result is "1".

This is failing on the line var regex... with the error:

SyntaxError: Invalid regular expression: /(?<![\w+#])c\+\+(?![\w+#])/: Invalid group 

I fail to see what I need to change to make my boundary work, can anyone help me?

尝试类似的方法:

var regex = new RegExp("([^\\w#]|^)c\\+\\+(?=[^\\w#]|$)", "g");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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