Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using negative lookbehind and lookahead in html5 pattern

I have tried looking over quite a lot of regex guides on how to use the negative lookbehind and lookahead in my regex function for html5 pattern.

I am trying to match the following pattern, where the string has to start and end with a [a-z] letter. The string can be up to 30 characters long. Can also include the symbol: -, however it can never have more than one - in a row.

Sooo, what I came up with so far is this:

^[a-z][a-z(?<!-(-)?!-)]{0,28}[a-z]$

Now I could not get the lookahead and lookbehind so work properly and I am not quite sure if I implemented the max 30 characters correctly. However, I have tried starting and ending with [a-z] and it works fine.

Some example strings:

'a-b' => true
'a-' => false
'-a' => false
'a--b' => false
'ab-cd' => true
'abc' => true
'a-b-c' => true
like image 420
Gjert Avatar asked Jan 21 '26 02:01

Gjert


2 Answers

You need to use

^(?!.{31})[a-z]+(?:-[a-z]+)*$

See the regex demo

Note that in an HTML5 pattern attribute, the anchors are usually not required as the pattern is anchored on both sides by default.

Details

  • ^ - start of string
  • (?!.{31}) - there cannot be 31 chars other than line break chars (this (?!...) is a negative lookahead that fails the match if its pattern is matched) (you may also use a positive lookahead - (?=.{1,30}$) - that requires 1 to 30 chars in the string)
  • [a-z]+ - 1 or more lowercase ASCII letters
  • (?:-[a-z]+)* - zero or more sequences of:
    • - - a hyphen
    • [a-z]+ - 1 or more lowercase ASCII letters
  • $ - end of string.
like image 63
Wiktor Stribiżew Avatar answered Jan 23 '26 21:01

Wiktor Stribiżew


You can use this pattern:

([a-z]|\b-\b){1,30}

The word boundaries prevent hyphens to be consecutive or to be at the string limits.

Note that ^ and $ are not needed in the pattern attribute since they are implicit.

demo

like image 45
Casimir et Hippolyte Avatar answered Jan 23 '26 21:01

Casimir et Hippolyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!