r/learnjava • • Jul 06 '21

Please explain this code involving the Regex - Compile method

What do the characters inside the braces exactly mean in the below code? Please explain each character. Or maybe link an article where this (the method) is explained in detail.

Pattern p = Pattern.compile("<(.+)>([^<>]+)(</\\1>)"); 

I tried finding it for an hour but can't find a proper explanation for this.

The whole code: LINK.

1 Upvotes

4 comments sorted by

8

u/_Atomfinger_ Jul 06 '21

You can use online tools, such as Regex101 to see what the regex does and play around with it:
https://regex101.com/

2

u/Incomplete-Sentenc Jul 06 '21

Thanks. I will check it out.

4

u/Hour-Positive Jul 06 '21

You need to work on your google-fu.

3

u/10-kinds-of-people Jul 06 '21

I hope this isn't considered a "complete solution." Please delete if so.

<(.+)>

Match a literal <, capture one or more characters, match a literal >

([^<>]+)

Capture one or more characters that are not < or >

(</\\1>)

Capture a literal </, then match the first capture (anything between the angle brackets), then match a literal >

I believe this pattern is trying to match matching HTML tags, but it will fail to match a tag like this:

<a href="some url">Some text</a>

Can you see why?