1

For example, here is a string representing an expression:

var str = 'total = sum(price * qty) * 1.09875';

I want to extract variables (i.e., 'total', 'price' and 'qty' but not 'sum' since 'sum' is a function name) from this expression. What is the regexp pattern in javascript? Variable name consists of letters, digits, or the underscore, beginning with letters or the underscore.

1
  • it's easy to write one for this specific case, but very very hard to write a generalized version. Commented Apr 9, 2010 at 19:37

1 Answer 1

4
return "total = sum(price * qty) * 1.09875".match(/[a-z_]\w*(?!\w*\s*\()/ig);

Here,

  1. [a-z_] matches 1 letter or 1 underscore,
  2. \w* matches 0 or more letters, digits or underscore (\w means [a-zA-Z0-9_])
  3. (?!…) is a negative lookahead. The match will fail if the stuff inside is matched.
  4. \w*\s*\( matches some letters, followed by some spaces, and then an (. This allows function names to be rejected.
Sign up to request clarification or add additional context in comments.

Comments

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.