0

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.

Rollerball
  • 12,618
  • 23
  • 92
  • 161

2 Answers2

6

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*.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • Hi Amber, you are right! but why it happens!? it was expanded in animable.class a class file of an interface i created time ago. Is there any way to clear that cache of unwanted shortcuts in the shell? – Rollerball Feb 16 '13 at 21:04
  • `*` is a wildcard that's built into the shell, not a specific shortcut. `a*` to the shell means "any files in the current directory that start with `a`". You need to quote your arguments if you don't want wildcards to be expanded. – Amber Feb 16 '13 at 21:05
0

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

Alex
  • 2,126
  • 3
  • 25
  • 47