RegExp获取以冒号分隔的键值对中的文本 [英] RegExp to get text in a key value pair separated by a colon
本文介绍了RegExp获取以冒号分隔的键值对中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里有我的Regexp示例: https://regex101.com/r/kE9mZ7/1
I have my Regexp example here: https://regex101.com/r/kE9mZ7/1
对于以下字符串:
key_1:一些文本,可能是逗号,以分号结尾;key_2:可能没有结尾分号的文本,但可能是
key_1: some text, maybe a comma, ending in a semicolon; key_2: text with possibly no ending semicolon, but could be
我想做以下事情:
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社区可以提供帮助!
My regexp is definitely wrong, hoping the SO community can help!
谢谢!
推荐答案
以下是提取这些值的正则表达式方法:
Here is a regex way to extract those values:
/(\w+):\s*([^;]*)/gi
或(因为标识符应以 _
或字母开头):
or (as identifiers should begin with _
or a letter):
/([_a-z]\w*):\s*([^;]*)/gi
这是一个 regex演示
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 +个除;
以外的字符.使用否定字符类消除了对其后跟(?:$ |;)
组的惰性点匹配的需要.注意,该*
量词使该值成为可选值.如果需要,请使用+
.
([_a-z]\w*)
- Group 1 matching an identifier starting with_
or a letter and followed with 0+ alphanumeric/underscore symbols:
- a colon\s*
- 0+ whitespaces([^;]*)
- 0+ characters other than;
. The use of a negated character class eliminates the need of using lazy dot matching with(?:$|;)
group after it. NOTE that*
quantifier makes the value optional. If it is required, use+
.
这篇关于RegExp获取以冒号分隔的键值对中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文