Finding substring in RegEx Java

后端 未结 5 513
北海茫月
北海茫月 2021-01-24 02:45

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.

I came up with the R

5条回答
  •  清酒与你
    2021-01-24 03:04

    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.

提交回复
热议问题