问题描述
我正在通过在两个词之间添加一个空格来解决我的问题.
I am driving my question from add a space between two words.
要求:拆分驼峰式字符串并在大写字母之前放置空格,然后是小写字母或可以什么都没有.大写字母之间不应有空格.
Requirement: Split a camel case string and put spaces just before the capital letter which is followed by a small case letter or may be nothing. The space should not incur between capital letters.
例如:CSVFilesAreCoolButTXT
是我想以这种方式产生的字符串 CSV Files Are Cool But TXT
eg: CSVFilesAreCoolButTXT
is a string I want to yield it this way CSV Files Are Cool But TXT
我是这样开普通快车的:
I drove a regular express this way:
"LightPurple".replace(/([a-z])([A-Z])/, '$1 $2')
如果您有 2 个以上的单词,则需要使用 g 标志来匹配所有单词.
If you have more than 2 words, then you'll need to use the g flag, to match them all.
"LightPurpleCar".replace(/([a-z])([A-Z])/g, '$1 $2')
如果想拆分像 CSVFile
这样的词,那么你可能需要使用这个正则表达式:
If are trying to split words like CSVFile
then you might need to use this regexp instead:
"CSVFilesAreCool".replace(/([a-zA-Z])([A-Z])([a-z])/g, '$1 $2$3')
但它仍然不能满足我提出的要求.
But still it does not serve the way I have put my requirements.
推荐答案
var rex = /([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g;
"CSVFilesAreCoolButTXT".replace( rex, '$1$4 $2$3$5' );
// "CSV Files Are Cool But TXT"
还有
"CSVFilesAreCoolButTXTRules".replace( rex, '$1$4 $2$3$5' );
// "CSV Files Are Cool But TXT Rules"
与正则表达式匹配的主题字符串的文本将被替换字符串'$1$4 $2$3$5'
替换,其中$1
,$2
等指的是与模式的捕获组()
匹配的子字符串.
The text of the subject string that matches the regex pattern will be replaced by the replacement string '$1$4 $2$3$5'
, where the $1
, $2
etc. refer to the substrings matched by the pattern's capture groups ()
.
$1
指的是第一个 ([AZ])
子模式匹配的子串,$3
指的是匹配的子串第一个 ([az])
子模式等
$1
refers to the substring matched by the first ([A-Z])
sub-pattern, and $3
refers to the substring matched by the first ([a-z])
sub-pattern etc.
由于替换字符 |
,要进行匹配,正则表达式必须匹配 ([AZ])([AZ])([az])
子模式或 ([az])([AZ])
子模式,因此如果匹配,多个捕获组将保持不匹配.可以在替换字符串中引用这些捕获组,但它们对其没有影响 - 实际上,它们将引用一个空字符串.
Because of the alternation character |
, to make a match the regex will have to match either the ([A-Z])([A-Z])([a-z])
sub-pattern or the ([a-z])([A-Z])
sub-pattern, so if a match is made several of the capture groups will remain unmatched. These capture groups can be referenced in the replacement string but they have have no effect upon it - effectively, they will reference an empty string.
替换字符串中的空格确保每次匹配时都会在主题字符串中插入一个空格(尾随的 g
标志意味着正则表达式引擎将查找多个匹配项).
The space in the replacement string ensures a space is inserted in the subject string every time a match is made (the trailing g
flag means the regular expression engine will look for more than one match).
这篇关于使用正则表达式在驼峰式字符串中放置空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!