简体   繁体   English

如果不在特定的HTML标签内,则匹配正则表达式

[英]Match Regex if not inside specific HTML tag

I would like to get special formatted strings ( {string} ) out of the HTML which are not inside a specific HTML tag. 我想从HTML中获取特殊格式的字符串( {string} ),这些{string}不在特定的HTML标记内。

For example I would like to match {test} and not <var>{test}</var> . 例如,我想匹配{test}而不匹配<var>{test}</var>

Therefore I am using the following regex: (excluding is done with ?! ) 因此,我使用以下正则表达式:(不包括使用?!完成)

(?!<var>)\{\S+?\}(?!<\/var>)

So this works very well for texts with spaces, but if I have something like (where there is no space in-between): 因此,这对于带空格的文本非常有效,但是如果我有类似的内容(中间没有空格):

<var>{name}</var>{username} 

it matches two {} -strings: {name}</var>{username} 它匹配两个{}字符串: {name}</var>{username}

How can I just match {username} here? 如何在这里匹配{username}

Update: If I need to do something like this 更新:如果我需要做这样的事情

<var.*?<\/var>|(\{\S+?\})

How can I get the matched values, because the matched index depends on the position. 如何获得匹配的值,因为匹配的索引取决于位置。

Examples: 例子:

Match 1: 比赛1:

"{username}<var>{name}</var>".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["{username}", "<var>{name}</var>"]

Match 2: 比赛2:

"<var>{name}</var>{username}".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["<var>{name}</var>", "{username}"]

Current Solution: 当前解决方案:

angular.forEach(html.match(regex), function (match) {
  if(match.substring(0, 4) !== '<var') {
    newAdded = match;
  }
});

Is this really the 'best' solution for JavaScript? 这真的是JavaScript的“最佳”解决方案吗?

Here is how you can achieve this using the following regex: 这是使用以下正则表达式可实现此目的的方法:

/<var.*?<\/var>|(\{\S+?\})/g;

 var s = '<var>{name}</var>{username}<var>{newname}</var>{another_username}'; var log = []; var m; var regex = /<var.*?<\\/var>|(\\{\\S+?\\})/g; while ((m = regex.exec(s)) !== null) { if ( m[1] !== undefined) { log.push(m[1]); } } alert(log); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM