How do I group optional strings together

Viewed 39

I need a regular expression which validates
"Optional str1 as string = ''",
but also
"str2 as string" and also
"str3 as boolean, Optional dtm as date = Now"

So when "Optional" is used there must be a "=" sign
But "Optional" is optional

This is what i have tried:

(Optional\s|)(.*)(\s=\s|)(.*)

and this is not right. It validates too much.

Any hints?

1 Answers

You can use an anchor ^ to assert the start of the string.

Then either match the string if it contains Optional followed by an equals sign in the string, or use a negative lookahead (if supported) and match the whole line if it does not contain Optional using an alternation |

^(?:.*\bOptional\b.*\s=\s.*|(?!.*\bOptional\b).+)

Explanation

  • ^ Start of string
  • (?: Non capture group
    • .*\bOptional\b.*\s=\s.* Match the whole line if it contains Optional and an equals sign between whitespace chars
    • | Or
    • (?!.*\bOptional\b).+ Match the whole line if it does not contain Optional
  • ) Close non capture group

Regex demo

Related