java子字符串方法中的OR条件
当使用带有开始和结束索引的java子字符串方法解析动态输入字符串时,我们可以在子字符串方法的结束索引中使用或条件吗?这意味着对于我的用例,结束索引可以是''或' 我的输入字符串有以下两种格式java子字符串方法中的OR条件,java,string,Java,String,当使用带有开始和结束索引的java子字符串方法解析动态输入字符串时,我们可以在子字符串方法的结束索引中使用或条件吗?这意味着对于我的用例,结束索引可以是''或' 我的输入字符串有以下两种格式 inputformat1 : Student(name: Joe, Batch ID: 23) is updated inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated 现在我有兴趣每次都获取“
inputformat1 : Student(name: Joe, Batch ID: 23) is updated
inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated
现在我有兴趣每次都获取“batchid”值。我想通过子字符串方法实现这一点。现在,如果我使用任何一个索引,即“)”或“,”我就可以得到批处理id值
有人能帮助我根据不同的结束索引批处理Id值吗?您可以使用
Math.min():
例如,您可以使用带有
replaceFirst
的正则表达式来解决您的问题
List<String> strings = Arrays.asList("Student(name: Joe, Batch ID: 23) is updated",
"Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated"
);
for (String string : strings) {
System.out.println(
string.replaceFirst(".*Batch ID:\\s+(\\d+).*", "$1")
);
}
如果需要多个组,也可以使用如下模式:
Pattern pattern = Pattern.compile("name:\\s+(.*?),.*?Batch ID:\\s+(\\d+)");
Matcher matcher;
for (String string : strings) {
matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(
String.format("name : %s, age : %s", matcher.group(1), matcher.group(2))
);
}
}
输出
23
2503
name : Joe, age : 23
name : John, age : 2503
最短的解决方案是使用
Math.min(tail\u old.indexOf(“)”),tail\u old.indexOf(“,”)
,不过这似乎是使用正则表达式的一个很好的用例。我可以使用相同的replaceFirst方法来获取名称值吗?请将名称的正则表达式更新为well@JavaLearner您如何了解?@JavaLearner在这种情况下,最好使用模式获取多个案例检查我的编辑!谢谢你的投入。一旦我获得足够的声誉,即15,我会投票表决答案吗
Pattern pattern = Pattern.compile("name:\\s+(.*?),.*?Batch ID:\\s+(\\d+)");
Matcher matcher;
for (String string : strings) {
matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(
String.format("name : %s, age : %s", matcher.group(1), matcher.group(2))
);
}
}
name : Joe, age : 23
name : John, age : 2503