java - 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 社区可以帮助我解决这个问题。
解决方案
您可以使用以下代码:
代码 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 个或多个小写字母。
或者使用String.split
相同的正则表达式并稍后加入:
代码 2
String out = Arrays.stream(s.split("(?=\\p{Lu})"))
.collect(Collectors.joining(" ")) + " " + s;
//=> "B By T The Way BByTTheWay"
推荐阅读
- python - 如何将整数列表拆分为两个独立的列表,它们的平均值大致相同?-Python
- php - php 7.4 install Imagick 找不到未定义的宏
- php - 在 symfony 中反序列化对象返回异常
- python - 使用python删除临时文件夹中的所有文件
- python - 将整个列表写入 Python 中的文本文件
- mysql - 运行查询时 5 秒后运行 MySQL 命令
- javascript - 使用 javascript 在表格中显示 csv 文件
- python - Python中的线性回归系数
- powershell - 有没有一种简单的方法可以让 Powershell 始终显示实际值?
- python - 将值转换为数据框或特定列中阈值的虚拟变量