我想根据两个条件拆分单词 1)按空间 2) 按单词 - 以 'n' 开头,以 't' 结尾,最后包含数字
基本上是付款条件
以下测试用例应该在我的案例中通过。有人可以解释为什么正则表达式不起作用吗?
String[] splitedWords3 = new String[] {"payment","term","nt","40","net","00","net", "30"};
Assertions.assertThat("payment term nt40 net00 net30".split("n[a-z]*t\\d+|\\S+")).isEqualTo(splitedWords3);
最佳答案
你不能做split
。你应该匹配你想要的并将其保存在List
中像这样的代码:
final String regex = "\\b(n\\w*t)(\\d+)\\b|(\\S+)";
final String string = "payment term nt40 net00 net30";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
List<String> words = new ArrayList<>();
while (matcher.find()) {
if (matcher.group(3) != null) {
words.add(matcher.group(3));
} else {
words.add(matcher.group(1));
words.add(matcher.group(2));
}
}
System.out.println(words);
输出:
[payment, term, nt, 40, net, 00, net, 30]
正则表达式详细信息:
-
\b
:字边界 -
(n\w*t)
:匹配以n
开头的单词直到我们得到t
并捕获第 1 组 -
(\d+)
:匹配单词末尾的 1 个以上数字并捕获到第 2 组 -
\b
:字边界 -
|
:或 -
(\S+)
:匹配 1 个以上非空白字符并捕获到第 3 组
关于java - 使用正则表达式分割字母数字字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59282999/