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

问题描述

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

示例:-

  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. (?<=\[)[ 指定正 lookbehind
  2. u 指定字符字面量 u
  3. \d+ 指定 one or more 位数字。
  4. (?=\])] 指定正向前瞻。

演示:

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