Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 匹配模式,但在一个条件正则表达式下除外_Javascript_Regex - Fatal编程技术网

Javascript 匹配模式,但在一个条件正则表达式下除外

Javascript 匹配模式,但在一个条件正则表达式下除外,javascript,regex,Javascript,Regex,我试图将模式与正则表达式匹配,除非模式被转义 测试文本: This is AT\&T&reg; is really cool Regex 你可以看到我的\&我正在手动转义。因此,不希望正则表达式匹配 正则表达式: const str = 'This is AT\&T&reg; is really cool Regex' str.replace(/\&(.*?)\;/g, '<sup>&$1;</sup>'); cons

我试图将模式与正则表达式匹配,除非模式被转义

测试文本:

This is AT\&T&reg; is really cool Regex
你可以看到我的\&我正在手动转义。因此,不希望正则表达式匹配

正则表达式:

const str = 'This is AT\&T&reg; is really cool Regex'

str.replace(/\&(.*?)\;/g, '<sup>&$1;</sup>');
const str='这是\&T®;真的很酷Regex'
str.replace(/\&(.*?)\/g,&$1;);
预期产量

This is AT&T<sup>&reg;</sup> is really cool Regex
这里是AT&T®;Regex真的很酷
我猜很难解释,但是当这个正则表达式的开头查找
&
并以
结尾时&
前面有at
\
类似于
\&
,则不匹配并查找下一个
\&(.*)

您可以使用 这个正则表达式与示例配合得很好
/(

编辑1
要在JS中解决问题,您可以使用除反斜杠之外的所有匹配项的
[^\\]
\/g
它适用于您的示例。

由于JavaScript不支持查找断言,因此可以添加一些自定义替换逻辑以获得所需的结果。为了测试目的,我使用不同类型html实体的示例更新了测试字符串:

const str='&T;his位于\\&T®;is&really&12345;&xAB05;\\\&cool;Regex'
console.log(str.replace(/&([a-z]+|[0-9]{1,5}|x[0-9a-f]{1,4});/ig,函数(m0,m1,索引,str){
返回(str.substr(索引-1,1)!='\\')?''+m0+'':m0;

}))
您的
str
不包含文本
\
。您需要在字符串文本中加倍
\
,以定义文本反斜杠。是否希望能够转义反斜杠?我希望\&永远不匹配并继续查找下一个&(.*)\;我想更好的例子是
var s=“这是\\®;®;真的很酷的Regex”
。您当前的问题可以通过
/&w+;/g
Regex解决。这不是一个问题,这是“为我编写代码”。更糟糕的是,您没有说您正在使用的语言,任务也没有明确说明(例如,您还没有回答transistor09的问题).Webstorm不喜欢,但我爱你!Thanks@MatthewHarwoodJavaScript没有look-behind.JavaScript lookbehind断言,因此应该对其进行测试。抱歉,我没有注意到它是JS。JS有解决方法(也请查看此线程中的其他答案)@Anton JS标记仅在一分钟前添加。