3

所以我在这方面有点挣扎。当我从某个地方拉弦时,决定在每个字符之间添加空格。

我只需要一个快速的正则表达式来:

  • 替换没有空格的单个空格
  • 用 1 个空格替换三重空格(因为" "变成"   "了添加的空格)。

有人可以帮助解决这个正则表达式吗?我知道如何为单个/多个空格执行此操作,但不会将 x 个空格变成 1 个空格。

4

4 回答 4

4

这有点棘手,但这是一个单一的正则表达式解决方案:

// becomes "test string"
"t e s t   s t r i n g".replaceAll("( )  | ", "$1");

示例:http: //ideone.com/O6DSk

这是因为如果匹配了三重空格,则其中一个空格将保存在捕获组 1 中,但如果匹配单个空格,则捕获组 1 为空。当我们用组的内容替换匹配项时,它将三个空格合二为一并删除单个空格。

于 2012-10-11T17:23:42.267 回答
3
s = s.replaceAll("\\s{3}", " ");  // Replace 3 spaces with one.

I assume you know to figure out, replacing single space with no space.

  • {n} matches exactly n spaces.
  • {0,n} matches 0 to n spaces.
  • {4,} matches 4 or more spaces.

To replace both single space with no space and 3 spaces with 1 space, you can use the below regex: -

s = "He llo   World";
s = s.replaceAll("(\\S)\\s{1}(\\S)", "$1$2").replaceAll("\\s{3}", " ");

System.out.println(s);

Ouput: -

Hello World

Order matters here. Because, 3 spaces will be converted to single space with the 2nd regex. If we use it before the 1st one, then eventually it will be replaced by no-space.

(\\S)\\s{1}(\\S) -> \\S is to ensure that only single space is replaced. \\S represents non-space character. If you don't have it, it will replace all the space character with no-space.

于 2012-10-11T17:17:28.317 回答
0

Replace single spaces with no space replace triple spaces with 1 space.

That's no job for regular expressions.

It is a job for regex after all.

input.replaceAll("(?<=\S) (?=\S)", "").replaceAll(" {3,}", " ");

The first regex replaces all single spaces that are preceded by a non-space (look-behind, (?<=\S)) and are followed by a non-space (look-ahead (?=\S)).

The other regex takes care of remaining triple spaces (or even more).

于 2012-10-11T17:16:38.773 回答
0

I think you can simply use replaceAll() with your desired combination with some workaround as below:

//locate 3 spaces and mark them using some special chars
myString = myString.replaceAll("   ", "@@@"); //use some special combination

//replace single spaces with no spaces
myString = myString.replaceAll(" ", "");

//now replace marked 3 spaces with one space
myString = myString.replaceAll("@@@", " "); //use the same special combination
于 2012-10-11T17:16:41.973 回答