Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple regex to match strings containing <n> chars

Tags:

java

regex

I'm writing this regexp as i need a method to find strings that does not have n dots, I though that negative look ahead would be the best choice, so far my regexp is:

"^(?!\\.{3})$"

The way i read this is, between start and end of the string, there can be more or less then 3 dots but not 3. Surprisingly for me this is not matching hello.here.im.greetings Which instead i would expect to match. I'm writing in Java so its a Perl like flavor, i'm not escaping the curly braces as its not needed in Java Any advice?

like image 315
JBoy Avatar asked Jan 15 '13 12:01

JBoy


2 Answers

You're on the right track:

"^(?!(?:[^.]*\\.){3}[^.]*$)"

will work as expected.

Your regex means

^          # Match the start of the string
(?!\\.{3}) # Make sure that there aren't three dots at the current position
$          # Match the end of the string

so it could only ever match the empty string.

My regex means:

^       # Match the start of the string
(?!     # Make sure it's impossible to match...
 (?:    # the following:
  [^.]* # any number of characters except dots
  \\.   # followed by a dot
 ){3}   # exactly three times.
 [^.]*  # Now match only non-dot characters
 $      # until the end of the string.
)       # End of lookahead

Use it as follows:

Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
like image 135
Tim Pietzcker Avatar answered Nov 08 '22 03:11

Tim Pietzcker


Your regular expression only matches 'not' three consecutive dots. Your example seems to show you want to 'not' match 3 dots anywhere in the sentence.

Try this: ^(?!(?:.*\\.){3})

Demo+explanation: http://regex101.com/r/bS0qW1

Check out Tims answer instead.

like image 1
Firas Dib Avatar answered Nov 08 '22 03:11

Firas Dib