【问题标题】:How to make this pattern [u123] in regex? [closed]如何在正则表达式中制作这种模式 [u123]? [关闭]
【发布时间】:2021-06-02 19:08:59
【问题描述】:

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

例子:-

  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

【问题讨论】:

  • 规格似乎不清楚。 123和342有什么特别之处? s.match(/\d+/) 微不足道地做到了这一点。如果您只想要以u 开头的括号中的内容,您可以添加外观s.match(/(?<=\[u)\d+(?=\])/g)
  • 谢谢,但我并没有真正问这意味着什么,我问的是模式背后的逻辑是什么。我猜魔术模式是<open bracket><literal u><some digits><close bracket>,但据我所知,它可能是任何东西。总是有3位数字吗? u 重要还是 [a123] 也匹配?您是否尝试过为此编写正则表达式?
  • 是的,你是对的,数字长度可以是任何长度,例如长度 1 或 3 或 10。

标签: java regex pattern-matching match


【解决方案1】:

您可以使用正则表达式(?<=\[)(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;
}

【讨论】:

  • 我找不到 results() ,我在 android java 中执行此操作!,我使用的是 java1.8
  • @iamkdblue - 我也发布了一个不使用Stream API 的解决方案。
  • Arvind 先生,我可以使用与数组拆分功能相同的正则表达式吗?
  • Kuldeep - 您的具体要求是什么?我建议您发布一个新问题,以便我或其他贡献者可以调查它。
  • 先生,我正在尝试在字符串中拆分 [uAnyNumber],我尝试了上述方法 reges 但没有得到相同的结果。你能帮帮先生吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2016-09-28
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多