'How to use or condition in typescript regex? [duplicate]

I'm trying to make sure only one type of special character (semi-colon, comma, or space) is used in a string.

e.g this should match as it only uses one type of special character (semi-colon): https://hello.com/example1;https://hello.com.com/example2;https://hello.com.com/example3

This should fail as it mixes two types of special characters (space and semi-colon)

https://hello.com/example1; https://hello.com.com/example2 ;https://hello.com.com/example3

This is my code - im using the yup schema builder for validation:

const myValidation = yup
.string()
.matches(/^([A-Za-z0-9://,\\.]|[A-Za-z0-9:// \\.]|[A-Za-z0-9://;\\.])+$/, 'Please separate each with a comma, space or semicolon')
.required();

When i only have /^([A-Za-z0-9://,\\.]+$/ it works correctly to only match the string if it has a only a comma as special character: https://hello.com/example1,https://hello.com.com/example2,https://hello.com.com/example3

but as soon as i add the other or conditions /^([A-Za-z0-9://,\\.]|[A-Za-z0-9:// \\.]|[A-Za-z0-9://;\\.])+$/ it starts allowing for semi-colon and space and comma special characters in the string at the same time (the invalid case)



Solution 1:[1]

You can use

/^[A-Za-z0-9:\/\\.]+(?=([,;\s])|$)(?:\1[A-Za-z0-9:\/\\.]+)*$/

See the regex demo. Details:

  • ^ - start of string
  • [A-Za-z0-9:\/\\.]+ - one or more ASCII letters, digits, :, /, \ or . chars
  • (?=([,;\s])|$) - a positive lookahead capturing the subsequent ,, ; or whitespace into Group 1, or matching end of string
  • (?:\1[A-Za-z0-9:\/\\.]+)* - zero or more sequences of the Group 1 value and then one or more ASCII letters, digits, :, /, \ or . chars
  • $ - end of string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew