gpt4 book ai didi

Java如何使用模式匹配器使用正则表达式来查找特定字符串

转载 作者:行者123 更新时间:2023-11-30 03:59:32 25 4
gpt4 key购买 nike

我不熟悉模式和匹配器,而且我很困惑这个问题。

我有一个想要在 Java 中操作的字符串。我明白我必须使用

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
String found = m.group(1).toString();
}

但是在我的字符串中,假设我有以下示例:

String in = "test anything goes here [A#1234|567]"; //OR
String in = "test anything goes here [B#1234|567]"; //OR
String in = "test anything goes here [C#1234|567]";

我想找到[A# | ][B# | ][C# | ] 在字符串中,如何使用正则表达式查找表达式?

最佳答案

在正则表达式中使用 [ABC]# 来匹配您的表达式。

Pattern p = Pattern.compile("(\\[[ABC]#.*?\\])");

如果字段是数字,那么您可以安全地使用 \d+

Pattern p = Pattern.compile("(\\[[ABC]#\\d+\\|\\d+\\])");

关于Java如何使用模式匹配器使用正则表达式来查找特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22301286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com