简体   繁体   English

正则表达式-在不是字母的任何字符之前添加空格

[英]regex - add space before any character that is not a letter

I have tried many things and am looking for a space to be added after any character that is not a letter. 我已经尝试了许多事情,并且正在寻找要在不是字母的任何字符之后添加空格的功能。 Currently I can replace all non letter characters with a space, but I want a space before the character is matched. 目前,我可以用空格替换所有非字母字符,但是匹配字符之前我需要一个空格。 At the moment I have: 目前,我有:

var str = 'div#some_id.some_class';
str = str.replace(/[^A-Za-z0-9]/g, ' ');

This provides me with the following, 这为我提供了以下内容,

div some_id some_class

however I am looking for the result to be div #some_id .some_class 但是我正在寻找结果是div #some_id .some_class

Any help would be greatly appreciated. 任何帮助将不胜感激。

You can use a negative lookahead for this: 您可以为此使用负前瞻

str = str.replace(/(?!\w|$)/g, ' ')
//=> "div #some_id .some_class"

(?!\\w|$) will match positions where next character is not alpha0numeral or end of line. (?!\\w|$)将匹配下一个字符不是alpha0numeral或行尾的位置。

Use groups and substitution 使用组和替代

 var str = 'div#some_id.some_class'; str = str.replace(/([^A-Za-z0-9])/g, ' $1'); console.log(str); 

You can try this : 您可以尝试以下方法:

str = str.replace(/([^a-zA-Z0-9_])/g, ' $1') //Omit 0-9 if you you want a space before them too

//OUTPUT: div #some_id .some_class

If you have an exact subset in mind, you'd probably be better of to specify just (but exactly) that (since Unicode has quite some characters you might not have even thought about.. think about things like unintended föóbàr to f ö ób àr , not even mentioning languages that don't really use Az ): 如果您有一个确切的子集,则最好只(但要准确地)指定(因为Unicode有很多您可能甚至都没有想到过的字符。)考虑一下诸如意料之外的föóbàrf ö ób àr ,甚至不提及实际上不使用Az语言):

 var str = 'div#some_id.some_class'; str = str.replace( /[.#]/g // add your exact subset to match on between the [ ] , ' $&' // $& inserts the matched substring (no capturing group needed) ); console.log(str); 

Also try at \\b word boundaries, where a \\W non word character is ahead: 还可以尝试\\b单词边界,其中\\W非单词字符在前面:

(?=\\W)\\b and replace matched position with a space ( regex101 ). (?=\\W)\\b并用空格( regex101 )替换匹配的位置。

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

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