简体   繁体   English

匹配此字符串没有lookbehind - Javascript正则表达式

[英]Matching this string without a lookbehind - Javascript Regex

We know that JavaScript doesn't support look-behinds. 我们知道JavaScript不支持后视。 I have been trying to match CC C part of the string. 我一直在尝试匹配字符串的CC C部分。 However, it matches C CC C as well. 但是,它也匹配C CC C

The regex should match CC or C only. 正则表达式应仅匹配CC或C.

String is KD IC CC C 字符串是KD IC CC C

Current Regex: (\\s*((CC)|(C)))+ 当前正则表达式: (\\s*((CC)|(C)))+

With a look-behind could have been: (\\s*((CC)|((?>=\\s|^)C)))+ 后视可能是: (\\s*((CC)|((?>=\\s|^)C)))+

What is an alternative here? 这里还有什么选择? I have tried non-capturing groups etc. but didn't work. 我尝试过非捕获组等但没有工作。

Because the function with this regex is used many times, I don't have the option to use other JavaScript functions. 因为使用这个正则表达式的函数很多次,所以我没有选择使用其他JavaScript函数。 The only way to achieve it is by using a regex. 实现它的唯一方法是使用正则表达式。

I am also using https://www.npmjs.com/package/xregexp of NodeJS. 我也在使用NodeJS的https://www.npmjs.com/package/xregexp Therefore, I might be able to use its additional functionality. 因此,我可以使用其附加功能。 Any help is appreciated. 任何帮助表示赞赏。

You can use the word boundary in this case to achieve the match you are looking for. 在这种情况下,您可以使用单词边界来实现您正在寻找的匹配。

 var str = 'KD IC CC C'; var found = str.match(/\\bcc?\\b/gi); // or you can use this: /\\bc{1,2}\\b/gi console.log(found); 

Looks like @procrastinator mentioned the same regex in the comments too. 看起来@procrastinator在评论中也提到了相同的正则表达式。

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

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