简体   繁体   中英

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 \\\\ . I'm using the following regex :

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

and the .match() function.
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 ]

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=(.*?[^\\\\])&/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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