I m looking fo a regex that not permit more than star character consecutive

Viewed 69

Hello I ' m looking for a regex that not permit write than more star character consecutive and not permit a string with just more star character. for example :

a*g*h*  // is allowed
***** // is not allowed
* //is not allowed
*a //. is allowed  

in this moment I have this regex :^([^*]*\*{1,2}[^*]*|\*[^*]*\*{1,2}[^*]*|\*\*[^*]+\*{1,2}[^*]*|[^*]*)$

Somebody can help me pls ?

3 Answers

You can do this using a lookahead condition with alternation:

^(?!\*$|.*\*\*).*

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!\*$|.*\*\*): Negative lookahead assertion that fails the match if we have just * before end or have ** anywhere in the input ahead
  • .*: Match 0 or more of any characters

You can use

^(?!\*+$)[^*]*(?:\*(?!\*)[^*]*)*$

See the regex demo (where [^*] is replaced with [^*\n] to stay on the same line since the demo is run against a single multiline string rather than a set of separate strings).

Details

  • ^ - start of string
  • (?!\*+$) - no * only string allowed
  • [^*]* - 0+ chars other than *
  • (?:\*(?!\*)[^*]*)* - zero or more repetitions of
    • \*(?!\*) - a * not followed with another *
    • [^*]* - 0+ chars other than *
  • $ - end of string.

This is the regex that works.

^(?!\*{2})[^\\\s][^*\\\s]*(?:\*(?!\*)[^*\\\s]*)*$
Related