1

I'd like to extract variable names from this scratch of code:

var a,b,c,  foo = "Test this is string";

I'd like the match result to contain a,b,c and foo and value optionally. I am able to split the string by a comma but I wonder if there's a way for this directly from the regex.

var\s+(.+)\s*,?\s*=.+;

You can test this out at http://rubular.com/ It shows me a,b,c,foo part but I'd like it to output in match groups like that:

  1. a
  2. b
  3. c
  4. foo

2 Answers 2

1

You can add more capturing groups to capture all the parts of the string the way you want:

var\s+(\w+),(\w+),(\w+),\s*(\w+)\s*=.+;

Output of the demo:

1.  a
2.  b
3.  c
4.  foo

Mind that if there is a non-specified number of arguments, this will not work.

As an alternative, use a regex with \G that forces consecutive matches:

(?:var\s+|(?<!^)\G)[,\s]*(\w+)

Output of another demo:

Match 1
1.  a
Match 2
1.  b
Match 3
1.  c
Match 4
1.  foo
Sign up to request clarification or add additional context in comments.

2 Comments

I like the second solution. Thank you so much!
Yes, it is safer: it checks if there is var , and then matches each sequence of alphanumerics separated with , and spaces.
1

You may use the below lookaround based regex.

string.scan(/(?<=[\s,])\w+(?=,?[^="']*=)/)

DEMO

1 Comment

Thanks! I didn't know ?= operator before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.