简体   繁体   中英

Regex to get string 'word' from `({#word#})` in Nodejs

How do I get string word from ({#word#}) using regex in Nodejs?

The regex I'm using right now is: /\\(({#[^)]+#})\\)/g It gives me string {#word#} from ({#word#}) .

How do I get the word out?

Use this regex:

/\(\{#(.*?)#\}\)/g

and grab the first capturing group match:

/\(\{#(.*?)#\})\)/g.exec("({#test#})")[1] === "test"

Capturing groups are expressions between parentheses in a regex that will save the part of the text that matches it. You can have multiple, but in this case we only need one.

The .*? is simple but not efficient, if you have a regex for word then use that instead.

Learn more about capturing groups:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM