3

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.

vrintle
  • 5,501
  • 2
  • 16
  • 46
  • I think it will be a lot more easier and convenient if you use [`String.split('-')`](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) and then check if the length is more than 6 or not. – vrintle Dec 11 '18 at 14:34
  • Thanks for your suggestion but it was a part of my regex that I needed –  Dec 11 '18 at 14:36
  • An alternative that doesn’t use a regular expression: `booleam matches = str.codePoints().filter(c -> c == '-').count() > 5;` – VGR Dec 11 '18 at 14:52

3 Answers3

1

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

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

Live Example

vrintle
  • 5,501
  • 2
  • 16
  • 46
0
"...".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 .*)

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

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

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268