Search code examples
javaregexexpressionlimit

java regular expression examples for match without length limitation


i trying to write a regular expression for match a string starting with letter "G" and second index should be any number (0-9) and rest of the string can be contain any thing and can be any length, i'm stuck in following code

String[] array = { "DA4545", "G121", "G8756942", "N45", "4578", "#45565" };

String regExp = "^[G]\\d[0-9]";

for(int i = 0; i < array.length; i++) 
{
    if(Pattern.matches(regExp, array[i])) 
    {
        System.out.println(array[i] + " - Successful");
    }
}

output:

G12 - Successful

why is not match the 3 index "G8756942"


Solution

  • G - the letter G
    [0-9] - a digit
    .* - any sequence of characters
    

    So the expression

    G[0-9].*
    

    will match a letter G followed by a digit followed by any sequence of characters.