-1

I'm validating the string and it can contain any character, it can start/end with a period but it should not contain multiple periods in a row. How would I achieve that?

Valid string:

  • {.tr.i._g

Not valid string:

  • {.tr..i._g
  • .tr...i.g

This is what I've got so far:

^.*[^\.\.]*.$

1
  • 1
    Hello again, Dot boy. Are you sure you can't just perform negative validation with that one? I mean to check if .. is found. Commented May 4, 2020 at 19:15

3 Answers 3

0

You may use this regex with a negative loikahead:

/^(?!.*\.\.).+/gm

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!.*\.\.): Negative lookahead to fail the match if 2 dots are foudn anywhere
  • .+: Match 1+ of any characcter
Sign up to request clarification or add additional context in comments.

6 Comments

And if the string were "abc\n..d", i.e. with a newline in it anywhere before the two periods?
Then just replace . with [^]. You should better ask OP if this is requirement. It appears from question that there is no \n in a row.
The OP said "I'm validating the string and it can contain any character ...". I don't go by two or three examples because "any character" would require an infinity of examples if you only go by the examples.
Why should I ask? My answer will work whether it's a requirement or not. It's your answer that is now in question.
I did not copy your answer. There aren't too many ways of doing this. And the point was that I think your answer is wrong because of the newline issue. And I presented an alternative to s mode.
|
0

This /^[^.]*(?:\.(?!\.)[^.]*)*$/

2 Comments

What if the input were "ab.c..d"? You can't use [^.]* because there might be an intervening period before you get to the two consecutive periods.
[^.] means no dot. Only dot allowed is checked for no adjacent (forward) dot.
-1

If it must contain at least one character, then:

/^(?!.*?\.\.).+$/s

^             # Matches start of string
(?!.*?\.\.)   # Negative lookahead assertion that the input does not contain two successive periods
.+            # Matches one or more characters
$             # Matches the end of the string

The s flag is required else . will not match a newline character. So if the string were, "abc\n..d", the s flag would be required to find the two successive periods.

If you do not want to use the s flag, then use instead of ., [\s\S], which will match any character:

/^(?![\s\S]*?\.\.)[\s\S]+$/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.