我这里有我的正则表达式示例:https://regex101.com/r/kE9mZ7/1
对于以下字符串:
key_1:一些文本,可能是逗号,以分号结尾; key_2:可能没有结束分号的文本,但也可以是
我想做如下的事情:
var regEx_attrVal = /[\w :].*?(?=;|$)/g;
var results = attrs.match(regEx_attrVal);
for(i=0;i<results.length;++i) {
var split = results[i].split(':');
preColon = split[0].trim();
postColon = split[1].trim();
//log preColon and postColon to console
}
最终结果应该是这样的:
//results[0]
preColon: key_1
postColon: some text, maybe a comma, ending in a semicolon
//results[1]
preColon: key_2
postColon: text with possibly no ending semicolon, but could be
我的正则表达式肯定是错误的,希望SO社区能够提供帮助!
Thanks!
这是提取这些值的正则表达式方法:
/(\w+):\s*([^;]*)/gi
或(因为标识符应以_
或一封信):
/([_a-z]\w*):\s*([^;]*)/gi
这里有一个正则表达式演示
var re = /([_a-z]\w*):\s*([^;]*)/gi;
var str = 'key_1: some text, maybe a comma, ending in a semicolon; key_2: text with no ending semicolon';
while ((m = re.exec(str)) !== null) {
document.body.innerHTML += m[1] + ": " + m[2] + "<br/>";
}
图案细节:
-
([_a-z]\w*)
- 第 1 组匹配以以下开头的标识符_
或一个字母,后跟 0+ 个字母数字/下划线符号
-
:
- 一个冒号
-
\s*
- 0+ 空格
-
([^;]*)
- 0+ 个字符以外的字符;
。使用一个否定字符类消除了使用惰性点匹配的需要(?:$|;)
其后分组。NOTE that *
量词使值成为可选的。如果需要,请使用+
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)