I've got a string
我有一个字符串
{'lalala'} text before \{'lalala'\} {'lalala'} text after
I want to get open bracket {
but only if there is no escape char \
before.
我想要获取左括号{但前提是之前没有转义字符。
Kind of /(?:[^\\])\{/
but it doesn't work at first statement.
/(?:[^ \ \])\ { /但它不工作首先声明。
2 个解决方案
#1
2
The typical approach is to match the non-\
preceding character (or beginning of string), and then put it back in your replacement logic.
典型的方法是匹配非\前的字符(或字符串的开头),然后将其放回替换逻辑中。
const input = String.raw`{'lalala'} text before \{'lalala'\} {'lalala'} text after`;
function replace(str) {
return input.replace(/(^|[^\\])\{'(\w+)'\}/g,
(_, chr, word) => chr + word.toUpperCase());
}
console.log(replace(input));
#2
1
That's where ^
comes in: it anchors a piece of regex to the start of the string (or the line, in m
multiline mode). Because a 'valid' opening bracket is either at the start of a string or after a non-\
character, we can use the following regex:
^进来的地方:它锚的正则表达式的字符串(或线,米多行模式)。因为“有效”左括号要么在字符串的开头,要么在非\字符之后,我们可以使用以下regex:
/(?:^|[^\\])\{/g
I added the g
global flag because we want to match all 'valid' opening brackets. Example use:
我添加了g全局标记,因为我们希望匹配所有“有效”的开始括号。使用示例:
console.log("{'lalala'} text before \\{'lalala'\\} {'lalala'} text after".match(/(?:^|[^\\])\{/g))
If you want to use the regex in a replace, you might want to capture the character before the bracket, as that gets replaced as well.
如果您希望在替换中使用regex,您可能希望在括号之前捕获字符,因为它也会被替换。
#1
2
The typical approach is to match the non-\
preceding character (or beginning of string), and then put it back in your replacement logic.
典型的方法是匹配非\前的字符(或字符串的开头),然后将其放回替换逻辑中。
const input = String.raw`{'lalala'} text before \{'lalala'\} {'lalala'} text after`;
function replace(str) {
return input.replace(/(^|[^\\])\{'(\w+)'\}/g,
(_, chr, word) => chr + word.toUpperCase());
}
console.log(replace(input));
#2
1
That's where ^
comes in: it anchors a piece of regex to the start of the string (or the line, in m
multiline mode). Because a 'valid' opening bracket is either at the start of a string or after a non-\
character, we can use the following regex:
^进来的地方:它锚的正则表达式的字符串(或线,米多行模式)。因为“有效”左括号要么在字符串的开头,要么在非\字符之后,我们可以使用以下regex:
/(?:^|[^\\])\{/g
I added the g
global flag because we want to match all 'valid' opening brackets. Example use:
我添加了g全局标记,因为我们希望匹配所有“有效”的开始括号。使用示例:
console.log("{'lalala'} text before \\{'lalala'\\} {'lalala'} text after".match(/(?:^|[^\\])\{/g))
If you want to use the regex in a replace, you might want to capture the character before the bracket, as that gets replaced as well.
如果您希望在替换中使用regex,您可能希望在括号之前捕获字符,因为它也会被替换。