简体   繁体   中英

Javascript regular expression to check whether a string is a combination of certain character

I want to check if a string starting from - ie hypen followed by any combination of the 3 characters ie a , p or m .

For example: -a , -p , -ap,-am,-apm etc.

Please help.

Use the following regex . This will check if the str starts with - and followed by any one of the a , p or m in any sequence having at least one character and maximum of three characters.

/^-[apm]{1,3}$/.test(str)

Regex Explanation

  1. / : Delimiter of regex
  2. ^- : Starts with -
  3. [apm] : Matches any characters inside [] in any sequence
  4. {1,3} : Matches preceding set of characters in the range from 1 to 3
  5. $ : End of the match

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