简体   繁体   English

正则表达式匹配特定模式(不包括特定模式)

[英]Regex match for a specific pattern excluding a specific pattern

I have sample string as : 我有示例字符串为:

  1. '&label=20:01:27&tooltext=abc\\&|\\|cba&value=6|59|58|89&color=ff0000|00ffff'
  2. '&label=20:01:27&tooltext=abc\\&|\\|cba&value=6|59|58|89'

My objective is to select the text from ' tooltext= ' till the first occurrence of ' & ' which is not preceded by \\\\ . 我的目标是从' tooltext= '中选择文本,直到' & '的第一个出现,而该字符之前没有\\\\ I'm using the following regex : 我正在使用以下正则表达式:

/(tooltext=)(.*)([^\\])(&)/ 

and the .match() function. .match()函数。
It is working fine for the second string but for the first string it is selecting upto the last occurrence of ' & ' not preceded by \\\\ . 对于第二个字符串,它工作正常,但对于第一个字符串,它选择的是最后一个出现的' & ',而不是\\\\

var a = '&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff',
b = a.match(/(tooltext=)(.*)([^\\])(&)(.*[^\\]&)?/i)

result, 结果,

b = ["tooltext=abc\&|\|cba&value=40|84|40|62&", "tooltext=", "abc\&|\|cba&value=40|84|40|6", "2", "&"]  

But what i need is: 但是我需要的是:

b = ["tooltext=abc&||cba&", "tooltext=", "abc&||cb", "a", "&"]

I think you can use a regex like this: 我认为您可以使用这样的正则表达式:

/tooltext=(.*?\\&)*.*?&/

[ Regex Demo ] [正则Regex Demo ]

and to always found a non-escaped & : 并总是找到一个非转义的&

/tooltext=(.*?\\&)*.*?[^\\]&/

It looks like your regex is matching all the way to the last & instead of the first one without a backslash in front of it. 看起来您的正则表达式一直与最后一个 &匹配&而不是第一个匹配,并且前面没有反斜杠。 Try adding the ? 尝试添加? operator to make it match as small as possible like so: 运算符以使其尽可能匹配,例如:

/(tooltext=)(.*?)([^\\\\])(&)/

And if you just want the text between tooltext= and & , try this to make it return the important part as the matched group: 并且,如果您只想在tooltext=&之间tooltext=文本,请尝试执行以下操作以使其以匹配组的形式返回重要部分:

/tooltext=(.*?[^\\\\])&/

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

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