我想将大多数字符串转换为小写,除了括号内的那些字符.将括号外的所有内容转换为小写后,我想删除括号.所以给出{H}ell{o} World输入应该Hello world作为输出.删除括号很简单,但是有没有办法用正则表达式选择性地使括号小写之外的所有内容?如果没有简单的正则表达式解决方案,那么在javascript中最简单的方法是什么?
你可以试试这个:
var str='{H}ell{o} World';
str = str.replace(/{([^}]*)}|[^{]+/g, function (m,p1) {
return (p1)? p1 : m.toLowerCase();} );
console.log(str);
Run Code Online (Sandbox Code Playgroud)
模式匹配:
{([^}]*)} # all that is between curly brackets
# and put the content in the capture group 1
| # OR
[^{]+ # anything until the regex engine meet a {
# since the character class is all characters but {
Run Code Online (Sandbox Code Playgroud)
回调函数有两个参数:
m完整的比赛
p1第一个捕获组
p1如果不为空,则返回p1整个匹配m小写。
细节:
"{H}" p1 contains H (first part of the alternation)
p1 is return as it. Note that since the curly brackets are
not captured, they are not in the result. -->"H"
"ell" (second part of the alternation) p1 is empty, the full match
is returned in lowercase -->"ell"
"{o}" (first part) -->"o"
" World" (second part) -->" world"
Run Code Online (Sandbox Code Playgroud)