Java splitting strings?

前端 未结 4 833
北恋
北恋 2021-01-23 04:08

I\'m trying split a string when ever a \" \" occurs, for example the sentence test abc. Then move the first letter in each word from first to last. I got the moving the letter t

4条回答
  •  别那么骄傲
    2021-01-23 05:02

    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:"
    

    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"
    

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


    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).

    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 @#$! -+"
    

    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"
    

    See also

    • Matcher.replaceAll
    • regular-expressions.info/Grouping and backreferences

提交回复
热议问题