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;
}