-3

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

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
iamkdblue
  • 3,448
  • 2
  • 25
  • 43
  • Spec seems unclear. What is special about 123 and 342? `s.match(/\d+/)` trivially does this. If you just want stuff in brackets starting with a `u`, you can add lookarounds `s.match(/(?<=\[u)\d+(?=\])/g)` – ggorlen Mar 04 '21 at 06:47
  • Thanks, but I'm not really asking what it means, I'm asking what the logic behind the pattern is. I'm guessing the magic pattern is `` but it could be anything as far as I can tell. Is there always 3 digits? Is the `u` important or does `[a123]` match as well? Have you tried writing a regex for this? – ggorlen Mar 04 '21 at 06:54
  • Yea you are right, digit length can be anything, like in leght 1 or 3 or 10 . – iamkdblue Mar 04 '21 at 06:55

1 Answers1

1

You can use the regex, (?<=\[)(u\d+)(?=\]) 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;
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110