在RegEx Java中查找子字符串 [英] Finding substring in RegEx Java

查看:211
本文介绍了在RegEx Java中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello I have a question about RegEx. I am currently trying to find a way to grab a substring of any letter followed by any two numbers such as: d09.

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

I came up with the RegEx ^[a-z]{1}[0-9]{2}$ and ran it on the string


sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0

sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0

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

However, it never finds r30, the code below shows my approach in 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));

它从不打印出任何东西,因为matcher从未找到子串(当我通过调试器运行它时),我做错了什么?

it never prints out anything because matcher never finds the substring (when I run it through the debugger), what am I doing wrong?

推荐答案

有三个错误:


  1. 您的表达式包含主播 ^ 仅匹配字符串的开头, $ 仅匹配结尾。所以你的正则表达式将匹配r30但不符合foo_r30_bar。您正在搜索子字符串,因此您应该删除锚点。

  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.

匹配应为 find

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

You don't have a group 1 because you have no parentheses in your regular expression. Use group() instead of 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

匹配文档


通过调用模式的匹配器方法从模式创建匹配器。一旦创建,匹配器就可以用来执行三种不同的匹配操作:

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:


  • 匹配方法尝试匹配整个输入序列

  • lookingAt方法尝试将输入序列(从头开始)与模式匹配。

  • find方法扫描输入序列寻找与模式匹配的下一个子序列。

这篇关于在RegEx Java中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆