首先,拆你的字符串到比赛和非比赛:
public static class Token {
public final String text;
public final boolean isMatch;
public Token(String text, boolean isMatch) {
this.text = text;
this.isMatch = isMatch;
}
@Override
public String toString() {
return text + ":" + isMatch;
}
}
public static List<Token> tokenize(String src, Pattern pattern) {
List<Token> tokens = new ArrayList<>();
Matcher matcher = pattern.matcher(src);
int last = 0;
while (matcher.find()) {
if (matcher.start() != last) {
tokens.add(new Token(src.substring(last, matcher.start()), false));
}
tokens.add(new Token(src.substring(matcher.start(), matcher.end()), true));
last = matcher.end();
}
if (last < src.length()) {
tokens.add(new Token(src.substring(last), false));
}
return tokens;
}
一旦做到这一点,你可以创建你可以遍历和处理列表。
例如,这样的代码:
Pattern digits = Pattern.compile("\\d+");
System.out.println(tokenize("1/2", digits));
...输出:
[1:true, /:false, 2:true]
所以字符串格式就是数字可以是分数? –
“1/9”,“12 \ 4”的输出应该是什么?或者它总是一样的'字符串格式'?如果不是,会发生什么? – amit
在非数字('[^ 0-9]')的正则表达式上拆分每个字符串。将每个数组编号项目添加到下一个数组的项目中相同的索引处。然后加入最初的分隔符?你将能够做到这一点的唯一方法就是如果你有相同数量的分割对象。 – brandonscript