[英]How to use a Regular Expression in JavaScript which contains special characters
Sorry, probably being dumb this morning, but I don't know much about regular expressions, but have created something I want to use with https://regex101.com/ 抱歉,今天早上可能很愚蠢,但是我对正则表达式了解不多,但是创建了一些我想与https://regex101.com/一起使用的东西
But... I can't use the code they suggest in Javascript without escaping it first. 但是...如果不先转义,我将无法使用他们在Javascript中建议的代码。
Here's the regex: (?<=color:\\s)([az]+)
这是正则表达式:
(?<=color:\\s)([az]+)
Which, does what I want (matching a word after color: in a CSS file) 哪个功能符合我的要求(在CSS文件中,在颜色后面匹配一个词)
But, the code they suggest to use in JS is: 但是,他们建议在JS中使用的代码是:
var re = /(?<=color:\s)([a-z]+)/g;
var str = ' color: black';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
The first line, won't work, so I escaped it to: var re = /\\(?<=color:\\s\\)([az]+)/i
which stops the Javascript error, but won't match the strings any more. 第一行不起作用,所以我将其转义为:
var re = /\\(?<=color:\\s\\)([az]+)/i
,它将停止Javascript错误,但与弦了。
What am I doing wrong? 我究竟做错了什么?
As an aside... can anyone point me to expanding this regex to exclude anything followed by a bracket? 顺便说一句...谁能指出我要扩展此正则表达式以排除括号后面的任何内容? I am trying to get color names only, so "color: black;"
我试图仅获取颜色名称,因此“颜色:黑色;” should match, also "box-shadow: black... etc" should match, but ideally, not "color: rgb(... etc"
应该匹配,“ box-shadow:black ... etc”也应该匹配,但是理想情况下,不应该匹配“ color:rgb(... etc”
It is true that JS does not support look-behinds, although there are workarounds : 确实,尽管有一些变通方法 ,JS不支持回溯:
In this case, it is much easier to use the capturing group: 在这种情况下,使用捕获组要容易得多:
var re = /\\bcolor:\\s*([az]+)/ig; var str = ' color: black'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } // m[1] is holding our value! document.getElementById("res").innerHTML = m[1]; }
<div id="res"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.