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.

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.