Nick
Nick

Reputation: 35

Need help writing a regex pattern

I am trying to find a pattern in a string that has a value that starts with ${ and ends with }. There will be a word between the curly brackets, but I won't know what word it is.

This is what I have \$\\{[a-zA-Z]\\}

${a} works, but ${aa} doesn't. It seems it's only looking for a single character.

I am unsure what I am doing wrong, or how to fix it and would appreciate any help anyone can provide.

Upvotes: 1

Views: 80

Answers (4)

Mulan
Mulan

Reputation: 135207

I think this could help you

var str = "The quick brown ${fox} jumps over the lazy ${dog}";

var re = /\$\{([a-z]+)\}/gi;

var match;

while (match = re.exec(str)) {
  console.log(match[1]);
}

Click Run code snippet and check your developer console for output

"fox"
"dog"

Explanation

  • + means match 1 or more of the previous term — in this example, match 1 or more of [a-z]
  • the (...) parentheses will "capture" the match so you can actually do something with it — in my example, I'm just using console.log to output it
  • the i modifier (at the end of the regexp) means perform a case-insensitive match
  • the g modifier means match all instances of this regexp in the target string
  • The while loop will continue running for each match that re.exec finds. Once re.exec cannot match another instance, it will return null and the loop will exit.

Additional information

Try console.log(match) using the code above. Each match comes with other useful information such as the string index where the match occurred

Gotchas

This will not work for nested ${} sets

For example, this regexp will not work on "The quick brown ${fox jumps ${over}} the lazy ${dog}."

Upvotes: 2

user636044
user636044

Reputation:

You're close!

All you need is to use a + to tell the expression that there will be one or more of whatever was just before it (in this case [a-zA-Z]) like this:

\${[a-zA-Z]+}

Upvotes: 1

Ian Agne
Ian Agne

Reputation: 160

A good website for regex reference and testing is http://rubular.com/

It looks like you need to add a +, which tells the regex to look for one or more of a character.

Try: \${[a-zA-Z]+}

Upvotes: 1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

You need to use * (zero or more) or + (one or more). So this [a-zA-Z] would be [a-zA-Z]+, meaning 1 or more letters. The entire regex would look like:

\$\{[a-zA-Z]+\}

Upvotes: 0

Related Questions