Issue
I'm struggling with a simple regex, for which I can't seem to get right.
I have some text like so:
This comment is great **[@madeUpUser1](/madeUpUser1)** You said something similar did you mate? **[@madeUpUser2](/madeUpUser2)**
What I would like to end up with is an array list containing the usernames inbetween the parentheses i.e.:
0.madeUpUser1
1.madeUpUser2
And here is the code I have so far:
List<String> matches = Pattern.compile("\\((.+?)\\)")
.matcher("This comment is great **[@madeUpUser1](/madeUpUser1)** You said something similar did you mate? **[@madeUpUser2](/madeUpUser2)**")
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
However what I'm getting back is this:
0."(/madeUpUser1)"
1."(/madeUpUser2)"
Again, where I want:
0.madeUpUser1
1.madeUpUser2
i.e. without the parentheses and without the forwardslash
Can anyone shed any light on what I'm doing wrong with my regex please?
Solution
Try this regex:
(?<=\\(/)[^)]+(?=\\))
Explanation
(?<=\\(/)- positive lookbehind to make sure that the current position is preceded by a(/[^)]+- matches 1 or more occurences(as many as possible) of any character that is not a)(?=\\))- positive lookahead to make sure that the current position is followed by a)
With the regex you are using, \\((.+?)\\), the following happens:
\\(- matches the opening parenthesis((.+?)- matches any character(except a new line character) 1 or more times, as few as possible. This subpattern will keep on expanding the match until it reaches the). That's why it is matching everything between the parenthesis(even the/)\\)- matches the closing parenthesis)
Answered By - Gurmanjot Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.