I have the following example string.
Hello {{ bob .name}} bob.name {{john.name}}
I have highlighted the part I'd like to match. It has to be between two curly brackets in each end and it has to be the first word before the dot.
I have tried this regex [^{{}}]+(?=\\}})
but it matches everything between the curly brackets like this
Hello {{ bob.name }} bob.name {{ john.name }}
It would also be very nice if I could provide a variable for which name to look for.
You can use this regex with a negated character class, a lookahead and a captured group:
/{{([^}.]+)(?=(?:(?!}}).)*}})/
([^}.]+)
: [^}.]+
matches a character that is not a dot and not a }
. (...)
captures in group #1. (?=(?:(?!}}).)*}})
is a lookahead that asserts we have a }}
ahead. To replace bob
that is inside {{...}}
use:
repl = str.replace(/({{)bob(?=(?:(?!}}).)*}})/gi, '$1newVal');
To match bob
inside {{...}}
use:
{{bob(?=(?:(?!}}).)*}})
You can use {{([^.]*)[^}]*}}
without any lookahead.
{{ }}
ensures you are inside double brackets.
([^.]*)
captures every character except a dot.
[^}]*
matches the rest of what's inside your double brackets.
The first returning group is what you want.
Use
(?<={{)([^{}]+?)(?=(?:\.(.*))?}})
It matches only bob and have 2 matchied groups: first - bob and second - name .
You can use it like this (used ES6 syntax):
const str = 'Hello {{bob.name}} bob.name {{john.name}}';
str.replace(/(?<={{)([^{}]+?)(?=(?:\.(.*))?}})/g, (allMatch, person, property) => {
console.log(`All match = ${allMatch}, person = ${person}, property = ${property}`);
}));
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.