How to make this pattern [u123] in regex?

I am trying to make a regex pattern for the given input:-

Example:-

  1. "Hi how are you [u123]"

    I want to take u123 from the above string.

  2. "Hi [u342], i am good"

    in this, I want to take u342 from the above string.

  3. I will count till 9, [u123]

    in this, I want to take u123 from the above string.

  4. 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?

Regular expression to extract text between square brackets

Answer

You can use the regex, (?<=[)(ud+)(?=]) which can be explained as

  1. (?<=[) specifies positive lookbehind for [.
  2. u specifies the character literal, u.
  3. d+ specifies one or more digits.
  4. (?=]) 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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *