如何在RegEx中替换“a b”内的空格以外的所有空格?

时间:2021-01-23 16:50:13

How would I replace all space characters with letter "_" except spaces inbetween characters "a" and "b" like this "a b".

如何用字母“_”替换所有空格字符,除了字符“a”和“b”之间的空格,如“a b”。

// this is what I have so far to save someone time (that's a joke)
var result:String = string.replace(/ /g, "_");

Oh this is in JavaScript.

哦,这是在JavaScript中。

2 个解决方案

#1


4  

Use this:

var result:String = string.replace(/([^a]) | ([^b])/g, "$1_$2");

A simplified explanation of the above is that it replaces a space that either:

上面的简化说明是它取代了以下任何一个空间:

  1. is preceded by a character other than a
  2. 之前是除了a之外的字符

  3. is followed by a character other than b
  4. 之后是b以外的字符

Note: to generalize the regex to include tabs and newlines, use \s, like this:

注意:要将正则表达式概括为包含制表符和换行符,请使用\ s,如下所示:

var result:String = string.replace(/([^a])\s|\s([^b])/g, "$1_$2");

#2


2  

Try this regex:

试试这个正则表达式:

/(?!a)\s(?!b)/g

Edit: This is not the best solution as KendallFrey pointed out.

编辑:这不是KendallFrey指出的最佳解决方案。

#1


4  

Use this:

var result:String = string.replace(/([^a]) | ([^b])/g, "$1_$2");

A simplified explanation of the above is that it replaces a space that either:

上面的简化说明是它取代了以下任何一个空间:

  1. is preceded by a character other than a
  2. 之前是除了a之外的字符

  3. is followed by a character other than b
  4. 之后是b以外的字符

Note: to generalize the regex to include tabs and newlines, use \s, like this:

注意:要将正则表达式概括为包含制表符和换行符,请使用\ s,如下所示:

var result:String = string.replace(/([^a])\s|\s([^b])/g, "$1_$2");

#2


2  

Try this regex:

试试这个正则表达式:

/(?!a)\s(?!b)/g

Edit: This is not the best solution as KendallFrey pointed out.

编辑:这不是KendallFrey指出的最佳解决方案。