BOSS
BOSS

Reputation: 1898

Regex: find text between two unknown tags

i have a string like this :

<!NAME!>Admin : <!NAME!><!MSG!>Hello Guys<!MSG!><!ADD-ACC!>BOSS<!ADD-ACC!>

I want to write a regex pattern that extracts text between two same tags like

<!NAME!>Admin : <!NAME!>
<!MSG!>Hello Guys<!MSG!>
<!ADD-ACC!>BOSS<!ADD-ACC!>

So i wrote this regex :

<!.*!>.*<!.*!>

But it gave me this result

<!NAME!>Admin : <!NAME!><!MSG!>Hello Guys<!MSG!><!ADD-ACC!>BOSS<!ADD-ACC!>

I understand why it did so, it is because

 <!NAME!> and <!ADD-ACC!> follows the regex pattern i am using.

So i was thinking of something like that in regex

<!XXX!>.*<!XXX!> where XXX is the same text between tags so that REGEX could find and extract those tags from text like how i want it to be done.

Upvotes: 2

Views: 1046

Answers (1)

Anirudha
Anirudha

Reputation: 32817

You can use backreference

(<!.*?!>).*?\1

.* is greedy quantifier which matches as much as possible

.*? is a lazy quantifier which matches as less as possible

(<!.*?!>) would capture a tag in group 1

We can refer to the captured value in group 1 within regex using \1..So,\1 refers to the first captured group value

Upvotes: 4

Related Questions