David542
David542

Reputation: 110083

Regex for three different enclosed text formats

Given the following three strings of text:

export DB_USER='aodhfoi2'
export DB_USER = aodhfoi2
export DB_USER="aodhfoi2"

Without the single or double quotes, the regex would be:

^export (?<key>[^= ]+)\s*=\s*(?<value>.+)$

What would be the correct regex with the enclosing quotes? I assume I would need a conditional to make sure that if it starts with a ' it ends with a ' and not a ".

Current regex here: https://regex101.com/r/yqvUIX/3

Upvotes: 0

Views: 30

Answers (1)

The fourth bird
The fourth bird

Reputation: 163197

If you want the value between the quotes as a separate value you could use another capturing group to capture an optional " or ' with a backreference to what is captured in the group to match the quotes.

^export (?<key>[^= ]+)\s*=\s*(['"]?)(?<value>\S+)\2

Explanation of the last part

  • (['"]?) Capture group 2, match optional ' or "
  • (?<value>\S+) Named group value, match 1+ times a non whitespace char
  • \2 Backreference to what is captured in group 2

Regex demo

Upvotes: 3

Related Questions