负面的前瞻性正则表达式 [英] Negative lookahead regex

查看:89
本文介绍了负面的前瞻性正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

I have a string like so:

<p>Year: ={year}</p>\
<p>Director: ={director}</p>\
<ul>@{actors}<li class="#{class}">={actor}</li>{actors}</ul>\

我想提取所有 = {match} 不在 @ {word} ... {word} 内,所以在这种情况下我想匹配 = {year} = {director} 但不是 = {actor } 。这是我到目前为止所得到的,但它不起作用。

And I want to extract all ={match} that are NOT inside @{word}...{word}, so in this case I want to match ={year} and ={director} but not ={actor}. This is what I got so far but it's not working.

/(?!@.*)=\{([^{}]+)\}/g

任何想法?

编辑:我目前的解决方案是在 @ {中找到所有 = {match} } ... {} 并用 =& 替换 = 。然后我抓住外面的那些,最后我回来把标记的那些恢复到原来的状态。

My current solution is to find all ={match} inside @{}...{} and replace the = with something like =&. Then I grab the ones that are outside and finally I come back and replace the flagged ones back to their original state.

推荐答案

你可以使用正则表达式将字符串分解为段,如下所示:

You can use regular expressions to break down the string into segments, like so:

var s = '<p>Year: ={year}</p> \
<p>Director: ={director}</p> \
<ul>@{actors}<li class="#{class}">={actor}</li>{actors}</ul>',
  re = /@\{([^}]+)\}(.*?)\{\1\}/g,
  start = 0,
  segments = [];

while (match = re.exec(s)) {
  if (match.index > start) {
    segments.push([start, match.index - start, true]);
  }
  segments.push([match.index, re.lastIndex - match.index, false]);
  start = re.lastIndex;
}

if (start < s.length) {
  segments.push([start, s.length - start, true]);
}

console.log(segments);

根据您的示例,您将获得以下细分:

Based on your example, you would get these segments:

[
    [0, 54, true], 
    [54, 51, false], 
    [105, 5, true]
]

布尔表示你是否在外 - - 或在 @ {} ... {} 段内。它使用反向引用将结尾与开头匹配。

The boolean indicates whether you're outside - true - or inside a @{}...{} segment. It uses a back-reference to match the ending against the start.

然后,根据段,您可以按照正常情况执行替换。

Then, based on the segments you can perform replacements as per normal.

这篇关于负面的前瞻性正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆