gpt4 book ai didi

java - 在 RegEx Java 中查找子字符串

转载 作者:行者123 更新时间:2023-11-29 10:04:09 28 4
gpt4 key购买 nike

您好,我有一个关于 RegEx 的问题。我目前正在尝试找到一种方法来获取任何字母后跟任意两个数字的子字符串,例如:d09。

我想出了 RegEx ^[a-z]{1}[0-9]{2}$ 并在字符串上运行它

sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0

但是,它从未找到 r30,下面的代码显示了我在 Java 中的方法。

Pattern pattern = Pattern.compile("^[a-z]{1}[0-9]{2}$");
Matcher matcher = pattern.matcher("sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0");

if(matcher.matches())
System.out.println(matcher.group(1));

它永远不会打印出任何东西,因为匹配器永远找不到子字符串(当我通过调试器运行它时),我做错了什么?

最佳答案

存在三个错误:

  1. 您的表达式包含 anchors . ^ 只匹配字符串的开头,$ 只匹配字符串的结尾。因此,您的正则表达式将匹配 "r30" 而不是 "foo_r30_bar"。您正在搜索一个子字符串,因此您应该删除 anchor 。

  2. 匹配应该是find

  3. 您没有第 1 组,因为您的正则表达式中没有括号。使用 group() 而不是 group(1)

试试这个:

Pattern pattern = Pattern.compile("[a-z][0-9]{2}");
Matcher matcher = pattern.matcher("sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0");

if(matcher.find()) {
System.out.println(matcher.group());
}

ideone


Matcher Documentation

A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

关于java - 在 RegEx Java 中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14027004/

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