简体   繁体   中英

How should I validate the complete string format using regex in JavaScript?

I want to validate the below string format:

'(:abc-xyz :abd-xyz-abx :v2-abc)'

I have tried creating a regex as:

const regex = RegExp('^[(][:][az|0-9|-]+(?: [:][az|0-9|-]+)*[)]$');

It is working for me for most of the cases but failing to validate when the string is:

string = '(:abc--xyz-:abc-xyz-abx-:v2-abc-)'

How should I validate the string so that '-' is allowed in between the word but not at the end of each word?

my requirement is:

string='(:abc-xyz :abd-xyz-abx :v2-abc)' -> Correct (only valid format others are incorrect).

example :
string='(:abc--xyz :abd-xyz-abx :v2--abc)' -> Incorrect
string='(:abc-xyz :abd-xyz-abx :v2-abc-)' -> Incorrect
string='(:abc-xyz:abd-xyz-abx :v2-abc-)' -> Incorrect

https://regex101.com/r/kJwWPt/1

You could use take the - out of the character class, and use optionally repeating groups where you prefix the : and -

Also the | in the character class will match the pipe literally, so you can omit that if you don't want to match it.

^\(:[a-z0-9]+(?:-[a-z0-9]+)*(?: :[a-z0-9]+(?:-[a-z0-9]+)*)*\)$

Explanation

  • ^ Start of string
  • \(: Match (:
  • [a-z0-9]+ Match 1+ times any of a-z0-9
  • (?:-[a-z0-9]+)* Optionally repeat - and 1+ times any of a-z0-9
  • (?: Non capture group
    • :[a-z0-9]+
    • (?:-[a-z0-9]+)* Optionally repeat - and 1+ times any of a-z0-9
  • )* Close non capture group and repeat 0+ times
  • \) Match )
  • $ End of string

Regex demo

 let pattern = /^\(:[a-z0-9]+(?:-[a-z0-9]+)*(?: :[a-z0-9]+(?:-[a-z0-9]+)*)*\)$/; [ "(:abc-xyz:abd-xyz-abx:v2-abc)", "(:abc--xyz-:abc-xyz-abx-:v2-abc-)", "(:abc--xyz:abd-xyz-abx:v2--abc)", "(:abc-xyz:abd-xyz-abx:v2-abc-)", "(:abc-xyz:abd-xyz-abx:v2-abc-)", ].forEach(s => console.log(`${s} ==> ${pattern.test(s)}`));

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