如何在正则表达式中制作这种模式 [u123]?

How to make this pattern [u123] in regex?

我正在尝试为给定的输入制作一个正则表达式模式:-

示例:-

  1. "Hi how are you [u123]"

    我想从上面的字符串中取出u123。

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

    在此,我想从上面的字符串中取出u342。

  3. "I will count till 9, [u123]"

    在此,我想从上面的字符串中取出u123。

  4. "Hi [u1] and [u342]"

    在此,我应该得到u1和u342

123和342是userId,可以是任意数字

我尝试了很多参考,但没有得到想要的结果

What's the regular expression that matches a square bracket?

Regular expression to extract text between square brackets

您可以使用正则表达式,(?<=\[)(u\d+)(?=\]) 可以解释为

  1. (?<=\[)[.
  2. 指定正数 lookbehind
  3. u指定字符字面量,u.
  4. \d+ 指定 one or more 位数。
  5. (?=\]) 指定 ].
  6. 的正前瞻

演示:

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

输出:

[u123]
[u342]
[u123]
[u1, u342]

请注意,Matcher#results 是作为 Java SE 9 的一部分添加的。另外,如果您对 Stream API 不满意,下面给出的解决方案没有使用 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;
}