我这里有我的正则表达式示例: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社区能帮忙!
谢谢!
最佳答案
这是提取这些值的正则表达式方法:
/(\w+):\s*([^;]*)/gi
或(因为标识符应以 _
或字母开头):
/([_a-z]\w*):\s*([^;]*)/gi
这是一个regex demo
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+ 个字符。 否定字符类的使用消除了在其后使用(?:$|;)
组的惰性点匹配的需要。 注意*
量词使值可选。如果需要,请使用+
。
关于javascript - 正则表达式获取由冒号分隔的键值对中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37157779/