简体   繁体   English

Javascript Regexp模式匹配

[英]Javascript Regexp pattern matching

"CamelCase".replace(/[AZ]/g, " $1")

Produces 产生

>>" $1amel $1ase"

How to replace all occurrence of camel cases. 如何替换所有发生的骆驼案。

You need bracket ( ) for grouping 您需要使用方括号()进行分组

"CamelCase".replace(/([A-Z])/g, " $1")

produces 产生

 Camel Case

You don't need to use a group. 您不需要使用群组。 Use $& to reference the whole match : 使用$&引用整个匹配项

"CamelCase".replace(/[A-Z]/g, " $&")

And when using /(?!^)[AZ]/g instead, you won't get that leading space: 而当使用/(?!^)[AZ]/g ,您将不会获得前导空间:

"CamelCase".replace(/(?!^)[A-Z]/g, " $&") === "Camel Case"

Maybe I'm missing something obvious but the previous answers do not act on CamelCased content but rather on all occurrences of uppercase letters. 也许我缺少明显的东西,但先前的答案并不针对CamelCased内容,而是针对所有大写字母。

This example preserves continuous blocks of capital letters and only separates a non-uppercase-letter followed by an uppercase letter (ie the CamelCase). 本示例保留连续的大写字母块,并且仅分隔非大写字母后跟大写字母(即CamelCase)。

"CamelCaseTestHTML".replace(/([^A-Z])([A-Z])/g, "$1 $2")
// Camel Case Test HTML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM