I am trying to make a regex pattern for the given input:-
Example:-
"Hi how are you [u123]"
I want to take u123 from the above string.
"Hi [u342], i am good"
in this, I want to take u342 from the above string.
"I will count till 9, [u123]
"
in this, I want to take u123 from the above string.
"Hi [u1] and [u342]
"
In this, I should get u1 and u342
123 and 342 is userId , it may be any number
I tried many references but I didn't get the desired result
What's the regular expression that matches a square bracket?
You can use the regex, (?<=\[)(u\d+)(?=\])
which can be explained as
(?<=\[)
specifies positive lookbehind for [
.u
specifies the character literal, u
.\d+
specifies one or more digits.(?=\])
specifies positive lookahead for ]
.Demo:
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String[] arr = { "Hi how are you [u123]", "Hi [u342], i am good", "I will count till 9, [u123]",
"Hi [u1] and [u342]" };
for (String s : arr) {
System.out.println(getId(s));
}
}
static List<String> getId(String s) {
return Pattern
.compile("(?<=\\[)(u\\d+)(?=\\])")
.matcher(s).results()
.map(MatchResult::group)
.collect(Collectors.toList());
}
}
Output:
[u123]
[u342]
[u123]
[u1, u342]
Note that Matcher#results
was added as part of Java SE 9. Also, if you are not comfortable with Stream
API, given below is a solution without using Stream
:
static List<String> getId(String s) {
List<String> list = new ArrayList<>();
Matcher matcher = Pattern.compile("(?<=\\[)(u\\d+)(?=\\])").matcher(s);
while (matcher.find()) {
list.add(matcher.group());
}
return list;
}