Regex matches the ending quote only if the quote is at the beginning

I want to match the next element with a regular expression

target="#MOBILE" 

and all valid options.

I wrote a regular expression

 target[\s\S]*#MOBILE[^>^\s]* 

which corresponds to the following

 target="#MOBILE" target = "#MOBILE" target=#MOBILE target="#MOBILE" (followed directly by >) 

but he does not match

 target=" #MOBILE " 

(pay attention to the extra space). It only matches

 target=" #MOBILE 

missing final quote

I need the ending expression [^>^\s]* match the quote only if it matches the quote at the beginning. It should also work with single quotes. The expression to be expressed must also end with a space or > char, as it is currently.

I am sure there is a way to do this, but I do not know how to do it. This is probably standard stuff - I just don't know it

I'm probably not sure that [^>^\s]* is the best way to complete if the regex gets into space or > char, but this is the only way to make it work.

+4
source share
3 answers

You can use backreference , similar to jensgram's suggestion:

 target\s*=\s*(?:(")\s*)?#Mobile\s*\1 

(?:(")\s*)? - An optional capturing-free group that contains a quote (which is removed) and additional optional spaces. If it matches, \1 will contain a quote.

Working example: http://regexr.com?2vkkq

The best alternative for .Net (mainly because you want single quotes, and \1 behaves differently for non-captured groups):

 target\s*=\s*(["']?)\s*?#Mobile\s*\1 

Working Example: Regular Storm

+2
source

Try the following if you need to verify that your quotes are in pairs:

 target\s*=\s*(['"])(?=\1)\s*#MOBILE\s*(?<=\1)\1 

But it really depends on whether your regex engine supports the positive look-(ahead|behind) syntax. And if it supports reverse binding.

+1
source

Without quotes target\s*=\s*#MOBILE

With double quotes, target\s*=\s*"\s*#MOBILE\s*"

With single quotes, target\s*=\s*'\s*#MOBILE\s*'

Together

(target\s*=\s*#MOBILE)|(target\s*=\s*"\s*#MOBILE\s*")|(target\s*=\s*'\s*#MOBILE\s*')

Or someone can make it more accurate.

0
source

Source: https://habr.com/ru/post/1389222/


All Articles