简体   繁体   English

正则表达式匹配括号内的正则表达式

[英]Regex match quotes inside bracket regex

I'm working on a regex that must match only the text inside quotes but not in a comment, my macthes must only the strings in bold 我正在研究一种仅与引号内的文本匹配但不能与注释匹配的正则表达式,我的Macthes必须仅以粗体显示字符串

< "love" ;> < “爱” ;>

>/*"love"*/< > / * “爱” * / <

<> 'love' <> <> '爱' <>

"lo “LO

more love 更多的爱

ve" 已经”

I'm stunck on this: 我对此感到震惊:

/(?:((\"|\')(.|\n)*?(\"|\')))(?=(?:\/\**\*\/))/gm

The first one (?:((\\"|\\')(.|\\n)*?(\\"|\\'))) match all the strings the second one (?=(?:\\/\\**\\*\\/)) doesn't match text inside quotes inside /* "mystring" */ 第一个(?:((\\"|\\')(.|\\n)*?(\\"|\\')))匹配所有字符串,第二个(?=(?:\\/\\**\\*\\/))/* "mystring" */引号内的文本不匹配/* "mystring" */

bit my logic is cleary wrong 我的逻辑很明显是错误的

Any suggestion? 有什么建议吗?

Thanks 谢谢

Maybe you just need to use a negative lookahead to check for the comment end */ ? 也许您只需要使用负数前瞻检查注释结尾*/

But first, I'd split the string into separate lines 但是首先,我将字符串分成几行

 var arrayOfLines = input_str.split(/\r?\n/);

or, without empty lines: 或者,没有空行:

 var arrayOfLines = input_str.match(/[^\r\n]+/g);

and then use this regex : 然后使用此正则表达式

["']([^'"]+)["'](?!.*\\*\\/)

Sample code: 样例代码:

var rebuilt_string = ''
var re = /["']([^'"]+)["'](?!.*\*\/)/g; 
var subst = '<b>$1</b>'; 

for (i = 0; i < arrayOfLines.length; i++)
{
   rebuilt_string = rebuilt_string + arrayOfLines[i].replace(re, subst) + "\r\n";
}

The way to avoid commented parts is to match them before. 避免注释部分的方法是先对其进行匹配。 The global pattern looks like this: 全局模式如下所示:

/(capture parts to avoid)|target/

Then use a callback function for the replacement (when the capture group exists, return the match without change, otherwise, replace the match with what you want. 然后,使用回调函数进行替换(当捕获组存在时,返回匹配而不做任何更改,否则,将匹配替换为所需的匹配。

Example: 例:

var result = text.replace(/(\/\*[^*]*(?:\*+(?!\/)[^*]*)*\*\/)|"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*'/g,
    function (m, g1) {
        if (g1) return g1;
        return '<b>' + m + '</b>';
});

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

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