且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java分割字符串?

更新时间:2023-02-23 10:27:35

您不必为此进行 split -tranform-join; replaceAll 可以一步完成.

You don't have to split-tranform-join for this; replaceAll can do this in one step.

    String text = "Skriv in en normal text:";
    text = text.replaceAll("(\\s*)(\\w)(\\w+)", "$1$3$2");
    System.out.println(text);
    // prints "krivS ni ne ormaln extt:"

正则表达式基本上捕获了3个组:

Basically the regex captures 3 groups:

\1 : (\s*) : any optional preceding whitespace
\2 : (\w)  : the head portion of each "word"
\3 : (\w+) : any tail portion of each "word"

然后,由于替换字符串使它变得清晰明了,因此您可以在 \ 2 \ 3 之间切换.

Then, as the replacement string makes it obvious and clear, you switch \2 and \3 around.

因此,应该清楚的是,带有捕获组的 replaceAll 是解决此问题的***,最易读的解决方案,但是正则表达式的具体内容取决于问题的规范.请注意,例如,上述正则表达式将 text:转换为 extt:(即,将冒号保留在原处).

So it should be clear that replaceAll with capturing group is the best, most readable solution for this problem, but what that regex is depends on the problem specification. Note that for example, the above regex transforms text: to extt: (i.e. the colon is kept where it is).

以下变体在空格 \ s 上拆分,并对非空格字符 \ S 的任何序列的头/尾重新排序.这应该与您当前的 split(") -transform-join解决方案相同:

The following variation splits on whitespaces \s, and reorders the head/tail of any sequence of non-whitespace characters \S. This should be identical to your current split(" ")-transform-join solution:

    String text = "bob: !@#$ +-";
    text = text.replaceAll("(\\s*)(\\S)(\\S+)", "$1$3$2");
    System.out.println(text);
    // prints "ob:b @#$! -+"

此变体可以对由单词边界 \ b 包围的任何单词字符 \ w + 序列进行切换.如果这是您的需要,那么这是最简单,最易读的解决方案.

This variation do the switch on any word character \w+ sequence surrounded by word boundary \b. If this is what you need, then this is the simplest, most readable solution for the job.

    String text = "abc:def!ghi,jkl mno";
    text = text.replaceAll("\\b(\\w)(\\w+)\\b", "$2$1");
    System.out.println(text);
    // prints "bca:efd!hig,klj nom"

另请参见