5

I'd like to know if this regex expression is correct for checking that a string doesn't start with a dot, doesn't end with a dot and contains at least one dot anywhere but not the start or end:

My issue is that I can't figure on how to check if there's 2 dots in a row.

/^([^.])+([.])+.*([^.])$/

5
  • Use this website to test your regex regex101.com Commented Dec 15, 2016 at 12:36
  • which programming language do you use? there could be easier solution.. Commented Dec 15, 2016 at 12:38
  • "I'd like to know if this regex expression is correct" -- there is only one way to know if it is correct or not (given that you didn't mention the program or language you want to use it with): pass it to the target program and see if it does what you want. Commented Dec 15, 2016 at 12:38
  • I'm using PHP sorry! But I want to know how to make so a string cannot have 2 dots in a row, so for example "test..test" wouldn't be acceptable but test.test would be acceptable. Commented Dec 15, 2016 at 13:29
  • @tempestor: See my answer for a solution that works exactly as you need. Use if (preg_match('~^[^.]+(?:\.[^.]+)+$~', $s, $matches)) { /* VALID! */ }. The 3rd $matches argument is actually not necessary. Commented Dec 15, 2016 at 13:35

2 Answers 2

4

It seems you need to use

^[^.]+(?:\.[^.]+)+$

See the regex demo

Details:

  • ^ - start of string
  • [^.]+ - 1+ chars other than a . (so, the first char cannot be .)
  • (?:\.[^.]+)+ - 1 or more (thus, the dot inside a string is obligatory to appear at least once) sequences of:
    • \. - a dot
    • [^.]+ - 1+ chars other than . (the + quantifier makes a char other than . appear at least once after a dot, thus, making it impossible to match the string with 2 dots on end)
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

3 Comments

would ^[^.]+(?:\.{0,x}[^.]+)+$ that not fix the 'must have .' problem? where x is max consecutive dots?
@user3012759: the limiting quantifier is redundant here because we need to match . once between 2 non-. symbols.
Ah, yes you're right OP asked about at least one, so yes your solution is perfectly fine.
2

You're close, have a try with:

^[^.]+(?:\.[^.]+){2,}$

It maches strings that have 2 or more dot, but not at the begining or at the end.

If you want one or more dot:

^[^.]+(?:\.[^.]+)+$

If you want one or two dots:

^[^.]+(?:\.[^.]+){1,2}$

Comments

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.