I want a JavaScript Regex which matches the character &
only if it occurs exactly one time followed by a alphanumeric character.
Examples:
&De&&let&&&e A&ll
→ Should only match &D
and &l
Hum&&an&s
→ should only match &s
This is what I have come up with but it is not quite right:
(?:[^\&]|^)\&([a-zA-Z0-9])
var strings = `&De&&let&&&e A&ll Hum&&an&s` console.log( strings.match(/(?:[^\\&]|^)\\&([a-zA-Z0-9])/g) )
You can turn the first group into a capturing group so that you could restore the value inside the replaced string with a $1
placeholder (also called replacement backreference ). In the similar way, you may restore the alphanumeric char captured into another group.
Here is an example of replacing &
with #
in the contexts you defined:
var strs = ['&De&&let&&&e A&ll', 'Hum&&an&s']; var rx = /(^|[^&])&([A-Z0-9])/gi; for (var s of strs) { console.log(s.replace(rx, "$1#$2")); }
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.