Regex: match string with or without quote

85 Views Asked by At

I'm trying to extract a value using regex. This value can be quoted or not:

For example:

foo: "bar" or foo: 'bar' or foo: bar

How can I extract only bar value?

Here is the regex I use:

How can I combine all three?

I don't want to use the first regex because it matches also the quotes "bar" and I only want to keep the string without the quotes.

Note that I would like to conserve the groups

3

There are 3 best solutions below

0
David Lounsbrough On

This regex would solve your specific use case: ^(foo):\s+['"]*([^'"]*) https://regex101.com/r/XJkzOj/1

If you give me more context about what you're trying to do I might be able to help more.

Good luck!

0
anubhava On

You may use this single regex with an additional capture group with an optional match and back-reference for all 3 cases:

^(foo):\s*(["']?)(\w.*?)(?<=\w)\2$

RegEx Demo

RegEx Details:

  • ^: Start
  • (foo): match foo in capture group #1
  • :\s*: Match : followed by 0 or more whitespaces
  • (["']?): Optionally match ' or " in capture group #2
  • (\w.*?): Match a word character followed by 0 more characters in capture group #3
  • (?<=\w): Make sure we have a word character on LHS of the current position
  • \2: Match same character as what we capture in group #2
  • $: End
1
Cary Swoveland On

The following regular expression will match the desired string.

rgx = /\Afoo:\s*(["']?)\K[^'"]*(?=\1\s*\z)/

Demo

For example:

"foo: 'bar'"[rgx] #=> "bar"
'foo: "bar"'[rgx] #=> "bar"
"foo: bar"[rgx]   #=> "bar"

The expression can be expressed in free-spacing mode to make it self-documenting:

rgx = /
  \A          # match beginning of the string
  foo:\s*     # match literal then >= 0 whitespaces
  (["']?)     # match ", ' or empty string and save to capture group 1 
  \K          # reset start of match and discard all previously-
              # consumed chars from the match that is returned
  [^'"]*      # match >= 0 characters other than ' and "
  (?=\1\s*\z) # positive lookahead asserts match is followed by
              # contents of capture group 1 then >= 0
              # whitespaces then end of string
/x            # invoke free-spacing regex definition mode