简体   繁体   中英

Javascript - regex to check if user write correct formated input

in my CLI users can specify what they want to use: A user command can look like this:

include=name1,name2,name3
category=name1,name2
category=name1

In another words, a command always consists of 3 parts:

  1. command name: can be just include or category
  2. = : is in every command
  3. name or names of things they want to use, split by ,

How can I test this to get always true but false on everything else.

I am really bad in regex but I tried something like this:

/\category|include=\w/.test(str);

to simply test, at least, the most easy alternative which would be category=name1 but without success.

Can someone help me with this?

You were on the right path. Here's a fixed regex:

/^(category|include)=\w+(,\w+)*$/.test(str);

Note:

  • the parens around the alternative parts
  • the + after the \\w so that you can have several characters
  • the optional (,\\w+)*
  • the start and end of string marks ( ^ and $ ) in order to check the whole string

You can use this regex for your requorement:

/^(category|include)=(\w+(?:,\w+)*)$/

RegEx Demo

\\w+(?:,\\w+)*) in the value part after = will allow 1 or more of comma separated words.

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