gat*_*lin 156 javascript regex regex-group taskwarrior
我是正则表达式的新手.我正在尝试解析以下类型的字符串:
description:"aoeu"
哪里有任意键:里面有"val"对.我想抓住关键名称和价值.对于那些好奇的我正在尝试解析任务战士的数据库格式.这是我的测试字符串:
description:"aoeu"这是为了强调除了空格之外的任何东西都可以在键或值中,冒号周围没有空格,值总是用双引号.在节点中,这是我的输出:
[key:"val" key2:"val2"]
Run Code Online (Sandbox Code Playgroud)
但description:"aoeu"也符合这种模式.我怎样才能把所有比赛都拿回来?
law*_*sea 211
继续调用re.exec(s)循环以获取所有匹配:
var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;
do {
m = re.exec(s);
if (m) {
console.log(m[1], m[2]);
}
} while (m);
Run Code Online (Sandbox Code Playgroud)
尝试使用这个JSFiddle:https://jsfiddle.net/7yS2V/
Ani*_*nis 100
str.match(pattern)将所有匹配作为数组返回.我想这是最简单的方法.
例如 -
const str = 'All of us except @Emran, @Raju and @Noman was there';
console.log(
str.match(/@\w*/g)
);
// Will log ["@Emran", "@Raju", "@Noman"]Run Code Online (Sandbox Code Playgroud)
Chr*_*phe 86
要遍历所有匹配项,您可以使用以下replace函数:
var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
s.replace(re, function(match, g1, g2) { console.log(g1, g2); });
Run Code Online (Sandbox Code Playgroud)
lov*_*soa 54
这是一个解决方案
var s = '[description:"aoeu" uuid:"123sth"]';
var re = /\s*([^[:]+):\"([^"]+)"/g;
var m;
while (m = re.exec(s)) {
console.log(m[1], m[2]);
}
Run Code Online (Sandbox Code Playgroud)
这是基于lawsea的答案,但更短.
请注意,必须设置`g'标志以将内部指针向前移动到调用之间.
noe*_*ego 15
str.match(/regex/g)
Run Code Online (Sandbox Code Playgroud)
将所有匹配作为数组返回.
如果出于某种神秘的原因,你需要附加的信息exec,作为以前答案的替代方案,你可以使用递归函数而不是循环,如下所示(它看起来也很炫).
function findMatches(regex, str, matches = []) {
const res = regex.exec(str)
res && matches.push(res) && findMatches(regex, str, matches)
return matches
}
// Usage
const matches = findMatches(/regex/g, str)
Run Code Online (Sandbox Code Playgroud)
如前面的注释中所述,重要的是g在正则表达式定义结束时在每次执行中向前移动指针.
Jef*_*kin 12
(意味着如果您的系统:Chrome、Node.js、Firefox 等支持 Ecmascript 2019 或更高版本)
使用新的yourString.matchAll( /your-regex/ ).
如果您的系统较旧,这里有一个易于复制和粘贴的功能
function findAll(regexPattern, sourceString) {
let output = []
let match
// make sure the pattern has the global flag
let regexPatternWithGlobal = RegExp(regexPattern,[...new Set("g"+regexPattern.flags)].join(""))
while (match = regexPatternWithGlobal.exec(sourceString)) {
// get rid of the string copy
delete match.input
// store the match data
output.push(match)
}
return output
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
console.log( findAll(/blah/g,'blah1 blah2') )
Run Code Online (Sandbox Code Playgroud)
输出:
[ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]
Run Code Online (Sandbox Code Playgroud)
基于Agus的功能,但我更喜欢只返回匹配值:
var bob = "> bob <";
function matchAll(str, regex) {
var res = [];
var m;
if (regex.global) {
while (m = regex.exec(str)) {
res.push(m[1]);
}
} else {
if (m = regex.exec(str)) {
res.push(m[1]);
}
}
return res;
}
var Amatch = matchAll(bob, /(&.*?;)/g);
console.log(Amatch); // yeilds: [>, <]
Run Code Online (Sandbox Code Playgroud)
可迭代项更好:
const matches = (text, pattern) => ({
[Symbol.iterator]: function * () {
const clone = new RegExp(pattern.source, pattern.flags);
let match = null;
do {
match = clone.exec(text);
if (match) {
yield match;
}
} while (match);
}
});
Run Code Online (Sandbox Code Playgroud)
循环使用:
for (const match of matches('abcdefabcdef', /ab/g)) {
console.log(match);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要一个数组:
[ ...matches('abcdefabcdef', /ab/g) ]
Run Code Online (Sandbox Code Playgroud)
如果你能使用matchAll这里的一个技巧:
Array.From有一个“选择器”参数,因此您可以将其投影到您真正需要的内容,而不是最终得到一系列尴尬的“匹配”结果:
Array.from(str.matchAll(regexp), m => m[0]);
Run Code Online (Sandbox Code Playgroud)
如果您已命名组,例如。( /(?<firstname>[a-z][A-Z]+)/g) 你可以这样做:
Array.from(str.matchAll(regexp), m => m.groups.firstName);
Run Code Online (Sandbox Code Playgroud)
我们终于开始看到一个内置matchAll函数,有关说明和兼容性表,请参见此处。截至2019年4月,似乎支持Chrome和Firefox,但不支持IE,Edge,Opera或Node.js. 好像它是在2018年12月起草的,所以给它一些时间来访问所有浏览器,但我相信它会到达那里。
内置matchAll函数很不错,因为它返回了iterable。它还会为每次比赛返回捕获组!所以你可以做类似的事情
// get the letters before and after "o"
let matches = "stackoverflow".matchAll(/(\w)o(\w)/g);
for (match of matches) {
console.log("letter before:" + match[1]);
console.log("letter after:" + match[2]);
}
arrayOfAllMatches = [...matches]; // you can also turn the iterable into an array
Run Code Online (Sandbox Code Playgroud)
似乎每个匹配对象都使用与相同的格式match()。因此,每个对象是匹配和捕获组的阵列,用另外的三个属性沿index,input和groups。所以看起来像:
[<match>, <group1>, <group2>, ..., index: <match offset>, input: <original string>, groups: <named capture groups>]
Run Code Online (Sandbox Code Playgroud)
有关更多信息,matchAll还有一个Google开发人员页面。也有可用的填充/垫片。
这是我获得比赛的功能:
function getAllMatches(regex, text) {
if (regex.constructor !== RegExp) {
throw new Error('not RegExp');
}
var res = [];
var match = null;
if (regex.global) {
while (match = regex.exec(text)) {
res.push(match);
}
}
else {
if (match = regex.exec(text)) {
res.push(match);
}
}
return res;
}
var regex = /abc|def|ghi/g;
var res = getAllMatches(regex, 'abcdefghi');
res.forEach(function (item) {
console.log(item[0]);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
166658 次 |
| 最近记录: |