简体   繁体   中英

JS RegEx allow certain characters and a few character only when part of a specific sequence

For quite a few hours I have been struggling with the following:

I want to use RegEx using JS to allow the following characters:

/^[a-zA-Z0-9 -.,]*$/igm

However I would also want to allow
or
, which means I would allow the character < & > and /, but only when in either of the two forms above (
or
). I was playing with something like;

/^(<(?=br \/>|br\/>))*&/img

Clearly this is not working, and I cannot seem to figure out how to test in one line of code whether the user input (a string) contains just the allowed characters plus the extra characters(<,>,/) but only when used as (
or
).

Your help is very much appreciated. Thank you.

You can use

^(?:<br ?\/>|[a-zA-Z0-9 .,-])*$

Details

  • ^ - start of string
  • (?:<br?\/>|[a-zA-Z0-9.,-])* - zero or more:
    • <br?\/> - <br , an optional space, />
    • | - or
    • [a-zA-Z0-9.,-] - a letter, digit, space, dot, comma or hyphen
  • $ - end of string.

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