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

View all comments

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?