简体   繁体   中英

RegEx: If first character is '%' or alphanumeric then

in nodejs, I have to following pattern

(/^(>|<|>=|<=|!=|%)?[a-z0-9 ]+?(%)*$/i

to match only alphanumeric strings, with optional suffix and prefix with some special characters. And its working just fine.

Now I want to match the last '%' only if the first character is alphanumeric (case insensitive) or also a %. Then its optionally allowed, otherwise it should not match.

Example:

Should match:

>test
!=test
<test
>=test
<=test
%test
test
%test%
test%

Example which should not match:

<test% <-- its now matching, which is not correct
<test< <-- its now **not** matching, which is correct

Any Ideas?

You can add a negative lookahead after ^ like

/^(?![^a-z\d%].*%$)(?:[><]=?|!=|%)?[a-z\d ]+%*$/i
  ^^^^^^^^^^^^^^^^^  

See the regex demo . Details :

  • ^ - start of string
  • (?![^az\\d%].*%$) - fail the match if there is a char other than alphanumeric or % at the start and % at the end
  • (?:[><]=?|!=|%)? - optionally match < , > , <= , >= , != or %
  • [az\\d ]+ - one or more alphanumeric or space chars
  • %* - zero or more % chars
  • $ - end of string

You might use an alternation | to match either one of the options.

^(?:[a-z0-9%](?:[a-z0-9 ]*%)?|(?:[<>]=?|!=|%)?[a-z0-9 ]+)$
  • ^ Start of string
  • (?: Non capture group
    • [a-z0-9%] Match one of the listed in the character class
    • (?:[a-z0-9 ]*%)? Optionally match repeating 0+ times any of the character class followed by %
    • | Or
    • (?:[<>]=?|!=|%)? Optionally match one of the alternatives
    • [a-z0-9 ]+ Match 1+ times any of the character class
  • ) Close non capture group
  • $ End of string

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM