简体   繁体   中英

Javascript Regex replace specific string with specific constraints

I have a string like so: {{q:6}}

I need to be able to make a regex to take it and turn it into this: "Question Here"

The Regex would need to ignore {{q: and would need to be [0-9] for any number from 0 to 100.

var final_value = value.replace(/^{{q:([0-9]+)$}}/g, 'question');

Using it in this context ^, but this isn't working. Any thoughts?

Thanks in advance!

EDIT: Final working answer:

value.replace(/\{\{q:([0-9]+)\}\}/g, question);

}}之后,必须将$符号

"{{q:6}}".replace(/^{{q:([0-9]+)}}$/g, 'question');// <= yields "question"
String final_value = "{{q:6}}\n{{q:39}}".replaceAll("\\{\\{q:([0-9]+)\\}\\}", "Question: $1");
System.out.println(final_value);

This is java, a general answer would be: "/\\{\\{q:([0-9]+)\\}\\}/g"

You need to escape your { and } .

Also if you want to limit from 0 to 100 inclusive, then you need to change:

[0-9]+

which will accept any string of digits to something like:

[1]?\d?\d

Which will accept 1 or not, a single digit (or not) and then a single digit.

Edit: and also @ruakh's comment about your placement of $ applies.

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