1

您好,我有一个关于 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));

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

4

5 回答 5

6

There are three errors:

  1. Your expression contains anchors. ^ matches only at the start of the string, and $ only matches at the end. So your regular expression will match "r30" but not "foo_r30_bar". You are searching for a substring so you should remove the anchors.

  2. The matches should be find.

  3. You don't have a group 1 because you have no parentheses in your regular expression. Use group() instead of group(1).

Try this:

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.
于 2012-12-25T01:32:47.403 回答
2

It doesn't match because ^ and $ delimite the start and the end of the string. If you want it to be anywhere, remove that and you will succed.

于 2012-12-25T01:33:19.493 回答
1
  1. Your regex is anchored, as such it will never match unless the whole input matches your regex. Use [a-z][0-9]{2}.

  2. Don't use .matches() but .find(): .matches() is shamefully misnamed and tries to match the whole input.

于 2012-12-25T01:33:28.583 回答
0

怎么样"[a-z][0-9][0-9]"?这应该找到您正在寻找的所有子字符串。

于 2012-12-25T01:41:34.750 回答
0

^[az]{1}[0-9]{2}$

sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0

据我所知

  • find thr first lower在它之后给出[s] 大写字母应该有两个数字,这意味着您的字符串的长度是并且始终是 3 个单词字符

也许如果我有更多关于您的字符串的数据,我可以提供帮助

编辑

如果您确定*点数,那么

更改此行

Matcher matcher = pattern.matcher("sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0");

Matcher matcher = pattern.matcher("sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0".split("\.")[0]);

笔记:-

使用我的解决方案,您应该省略模式的前导 ^

阅读此页面以了解拆分字符串

于 2012-12-25T13:26:49.330 回答