Pergunta

Do you know why in a simple regex pattern if put a*(quantifier) it does not match any result in the matcher even though it actually contains the character a; (in any case it should give back a result of having found an empty string as I am using ""). It works with other characters, for instance with r* and b* there is no problem. I am aware that it works if the content is put between quotes or parentheses.("a*"). Though just curious to know why it would work with b* without quotes and not with a* without quotes.

Code:

Pattern pat = Pattern.compile(args[0]);
        Matcher match = pat.matcher(args[1]);
while (match.find())
        {
            System.out.println("Indeed this the information I need:"+ match.group());

            System.out.println("Here it starts:"+match.start());
}       

I am aware that 'a' is a metacharacter but also 'e' and 'f' are and with them it works normally.

I insert as inputs : args[0] = a* args[1] = abba in the command line.

Any idea? Thanks in advance.

Foi útil?

Solução

Probably because the * is getting expanded by the shell from which you are running Java. Try printing out the contents of args[0], I think you'll find that the pattern you're matching against isn't the one you think you're matching against.

You could fix this by quoting your argument - 'a*' instead of just a*.

Outras dicas

In order to select something your regex has to be like: "(a*)" and you are interested in group(1)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top