用于查找字符串但不在引号中的正则表达式

Regular Expression to Find a String but not in quotes

本文关键字:正则表达式 查找 字符串 用于      更新时间:2023-09-26

我是正则表达式的新手,我正在寻找一种方法来检查字符串是否包含匹配项,但匹配项不应使用单引号或双引号。

ex:
var match = 'gs.info';
var example1 = 'var test=1; gs.info(test);'; // True
var example2 = 'var test="gs.info(test); blah blah"'; // false because it is in double quotes
var example3 = "var test='gs.info(test); blah blah'"; // false because it is in single quotes

此示例适用于:

var regex = /^('.*(["']['d'w's]+["'])?[^"''])*gs'.info('(["']*[^)"']*["']*'))('.*(["']['d'w's]+["'])?[^"''])*$/g;
regex.test('var test="gs.info(test); blah blah"');
regex.test('var test=''gs.info(test); blah blah''');

正则表达式的意思是: ^[^"']*:行首不是双引号或单引号且重复一到零次的任何内容, [^"']*$ :任何不是双引号或单引号的东西,直到重复一次或零次的行尾。

不要忘记转义点,因为此字符在正则表达式中具有特殊含义。