Reputation:
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
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);
}
Upvotes: 0
Reputation: 109547
"...".matches("(?s)([^-]*-){6}.*")
(?s)
dot-all, .
will also match line separators like \r
and n
.( )
, 6 times {6}
, any char .
0 or more times *
[]
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
Reputation: 5586
If you want to use Regex, then you could try the following:
^(.*?-){6,}.*$
Upvotes: 1