正则表达式在匹配后忽略一些上下文
regexp ignore some context after matching
我想解决 javascript 中的正则表达式问题:
忽略 } 字符用引号包裹的上下文。
但必须匹配引号外的 } 字符。
示例:
"The sentense { he said 'hello, {somebody}', she said 'hi, {somebody}' } got a something."
结果:
{ 他说'hello, {somebody}',她说'hi, {somebody}' }
感谢您的帮助
上下文有点模糊,但假设您希望结果包含(包括)outer 大括号内的所有内容,您可以只使用 /{.*}/g
.
这可以在下面看到:
var regex = /{.*}/g;
var string = 'The sentense { he said "hello, {somebody}" } got a something.';
console.log(string.match(regex)[0]);
或者如果你想获取所有三个组件,你可以使用稍微复杂一点的正则表达式
/({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g
:
分解:
({.*(?={))
- 将任何内容分组到第二个 {
(.*(?<=.*}))
- 抓住内部花括号内的所有内容并将其分组
(?:.*)
- 将任何内容分组到下一个 }
}
- 继续搜索下一个 }
(但不要将其分组)
(.*)
- 在此之后分组任何内容
这可以在JavaScript这里看到:
var regex = /({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g;
var string = 'The sentense { he said "hello, {somebody}" } got a something.';
string.replace(regex, function(match, g1, g2, g3) {
console.log(match);
console.log(g1);
console.log(g2);
console.log(g3);
});
并且可以看到正在 Regex101 here.
我想解决 javascript 中的正则表达式问题:
忽略 } 字符用引号包裹的上下文。 但必须匹配引号外的 } 字符。
示例: "The sentense { he said 'hello, {somebody}', she said 'hi, {somebody}' } got a something."
结果: { 他说'hello, {somebody}',她说'hi, {somebody}' }
感谢您的帮助
上下文有点模糊,但假设您希望结果包含(包括)outer 大括号内的所有内容,您可以只使用 /{.*}/g
.
这可以在下面看到:
var regex = /{.*}/g;
var string = 'The sentense { he said "hello, {somebody}" } got a something.';
console.log(string.match(regex)[0]);
或者如果你想获取所有三个组件,你可以使用稍微复杂一点的正则表达式 /({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g
:
分解:
({.*(?={))
- 将任何内容分组到第二个{
(.*(?<=.*}))
- 抓住内部花括号内的所有内容并将其分组(?:.*)
- 将任何内容分组到下一个}
}
- 继续搜索下一个}
(但不要将其分组)(.*)
- 在此之后分组任何内容
这可以在JavaScript这里看到:
var regex = /({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g;
var string = 'The sentense { he said "hello, {somebody}" } got a something.';
string.replace(regex, function(match, g1, g2, g3) {
console.log(match);
console.log(g1);
console.log(g2);
console.log(g3);
});
并且可以看到正在 Regex101 here.