gpt4 book ai didi

Java正则表达式捕获重复组

转载 作者:行者123 更新时间:2023-12-02 01:25:06 24 4
gpt4 key购买 nike

我无法通过正则表达式捕获第 2 组中的所有数据,包括所有字符、数字、空格和特殊字符

尝试过正则表达式

 final String regex = "^:(.*?)//(.*[\\s\\S]?)";
String line1 = ":Humpty Dumpty sat on a wall";
String line2 = "//Humpty Dumpty had a great fall";
String rhyme = line1 + line2+"\n"+ "ssdsds"+"\n";
final String value = rhyme.replaceAll(regex , "$2");
final boolean formatIdentified = rhyme.matches(formatRegex);
System.out.println(formatIdentified);//returns false

我期待的值(value)

"Humpty Dumpty had a great fall
ssdsds
"

更正后的正则表达式应采用格式 :abc//xxxx,输出应为 xxxx

最佳答案

String.replaceAllString.matches 完全有可能以不同的方式处理多行字符串的终止符,即换行符与字符串结尾,即为什么 value 可以打印预期结果,但 matches 打印 false。

我会更明确地直接使用PatternMatcher而不是通过String代理:

        String rhyme =
":Humpty Dumpty sat on a wall\n" +
"//Humpty Dumpty had a great fall\n" +
"ssdsds\n";

Pattern pattern = Pattern.compile("^:(.*?)//(.*[\\s\\S]?)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(rhyme);
if (matcher.find()) {
System.out.println(matcher.group(2));
} else {
System.out.println("[Pattern not found]");
}

这将输出:

   Humpty Dumpty had a great fall
ssdsds

如果您希望仅匹配以新行结尾,则只需将标志更改为 Pattern.MULTILINE。

   Pattern pattern = Pattern.compile("^:(.*?)//(.*[\\s\\S]?)", Pattern.MULTILINE);

将输出:

   Humpty Dumpty had a great fall

关于Java正则表达式捕获重复组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57591789/

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