1

In my current project I am confronted with the problem of having a string that can be constructed in 2 patterns. It consists of only one natural number, or 2 natural numbers with a '-' in between. I need to be able to distinguish between them. I would like to use the following code for this:

if (STRING.matches("*-*"))
{
    //Do something
} else {
    //Do something else
}

However, it gives me the following error:

Exception in thread "Thread-2" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

I also tried to put '#' at the beginning of the string ( of course I added it to the pattern), but this only caused the else part of the if-query to be executed.

Hope you can help me

isi_ko

1
  • 3
    Have you read the documetation for class java.util.regex.Pattern ? It explains java's regex syntax. Commented Apr 19, 2020 at 20:05

1 Answer 1

3

Your regex is incorrect because the asterisk is a metacharacter that needs a pattern before it. You can try something like this:

if (STRING.matches("[^-]*-[^-]*"))
{
    //Do something
} else {
    //Do something else
}

A better way would probably to use String#split("-") and put that into an array. Then you could check the length of that array to see how many numbers there and then use Integer.parseInt on each substring to obtain a natural number.

Another way would be to use a Matcher to find multiple groups. If (\d)* is the regex that matches a natural number, you can do this:

Pattern pattern = Pattern.compile("(\\d)*");
Matcher matcher = pattern.matcher(input);
matcher.find();
String first = matcher.group();
if (matcher.find()) {
  String second = matcher.group(); //this means there are two numbers
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked :D (Edit: I used the version with String.split("-");)

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.