user10776148
user10776148

Reputation:

java regex hyphen within string multiple times

I have a Java program that should match a string if it contains a hyphen for more than 5 times in it:

hello-hi-contains-more-than-five-hyphen

The words can contain any regular characters.

The regex should not match on this example:

hi-hello-233-here-example

I tried to write a regex like this:

.*-{6,}.*

But it doesn't works.

Upvotes: 3

Views: 1224

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98881

No need for expensive regex here, a simple split and length will do it, i.e.:

String subjectString = "hello-hi-contains-more-than-five-hyphen";
String[] splitArray = subjectString.split("-");
if(splitArray.length > 5){
    System.out.println(subjectString);
}

Java Demo

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

"...".matches("(?s)([^-]*-){6}.*")
  • (?s) dot-all, . will also match line separators like \r and n.
  • group ( ), 6 times {6}, any char . 0 or more times *
  • group with char set [] not ^ containing -, 0 or more times *, followed by -

For matches the regex must cover the entire string, so ^ (start) and $ (end) are already implied. (Hence the need for .*)

Upvotes: 0

vrintle
vrintle

Reputation: 5586

If you want to use Regex, then you could try the following:

^(.*?-){6,}.*$

Live Example

Upvotes: 1

Related Questions