首页 > 解决方案 > split String 如果得到任何大写字母

问题描述

我的字符串: BByTTheWay。我想拆分字符串as B By T The Way BByTheWay。这意味着如果我得到任何大写字母,我想拆分字符串,最后按原样放置主字符串。到目前为止,我在 java 中尝试过:

public String breakWord(String fileAsString) throws FileNotFoundException, IOException {

    String allWord = "";
    String allmethod = "";
    String[] splitString = fileAsString.split(" ");
    for (int i = 0; i < splitString.length; i++) {
        String k = splitString[i].replaceAll("([A-Z])(?![A-Z])", " $1").trim();
        allWord = k.concat(" " + splitString[i]);
        allWord = Arrays.stream(allWord.split("\\s+")).distinct().collect(Collectors.joining(" "));
        allmethod = allmethod + " " + allWord;
        //  System.out.print(allmethod);
    }
    return allmethod;

}

它给了我输出: B ByT The Way BByTTheWay . 我认为 stackoverflow 社区可以帮助我解决这个问题。

标签: javaregex

解决方案


您可以使用以下代码:

代码 1

String s = "BByTTheWay";
Pattern p = Pattern.compile("\\p{Lu}\\p{Ll}*");

String out = p.matcher(s)
     .results()
     .map(MatchResult::group)
     .collect(Collectors.joining(" "))
     + " " + s;

//=> "B By T The Way BByTTheWay"

RegEx\\p{Lu}\\p{Ll}*匹配任何 unicode 大写字母后跟 0 个或多个小写字母。

CODE DEMO


或者使用String.split相同的正则表达式并稍后加入:

代码 2

String out = Arrays.stream(s.split("(?=\\p{Lu})"))
    
.collect(Collectors.joining(" ")) + " " + s;
//=> "B By T The Way BByTTheWay"

推荐阅读