String.substring()OR运算符

问题描述 投票:-1回答:2

是否可以在substring中执行OR运算符?这是我的,但它不起作用

str.substring(str.indexOf("start")+1, str.indexOf("x|y"))
java string indexing
2个回答
4
投票

indexOf不够复杂,无法做到这一点。但是,您可以使用正则表达式来获取子字符串:

Pattern p = Pattern.compile("start(.*?)(?:x|y)");
Matcher m = p.matcher(str);
if (m.find()) {
    String sub = m.group(1);
}

Demo.


-1
投票

解:

-> "startthexstrayingx".replaceAll ("start([^xy]*(x|y)).*", "$1") 
|  Expression value is: "thex"
|    assigned to temporary variable $72 of type String

第一组从“开始”开始并捕获,直到满足第一个x或y。

使用String start的锚点,它将只捕获一个匹配项,而不管名称replaceAll:

-> "startstartthexstrayingstartAgainandynotyy".replaceAll ("^start([^xy]*(x|y)).*", "$1") 
|  Expression value is: "startthex"
|    assigned to temporary variable $77 of type String

Demo

从字面上看问题,模式必须是"^s(tart[^xy]*(x|y)).*"但我怀疑这不是故意的。

但不是那样的:

-> String str = "startthex|ystray"
|  Modified variable str of type String with initial value "startthex|ystray"
|    Update overwrote variable str

-> str.substring(str.indexOf("start")+1, str.indexOf("x|y"))
|  Expression value is: "tartthe"
|    assigned to temporary variable $62 of type String

-> String str = "startthexstray"
|  Modified variable str of type String with initial value "startthexstray"
|    Update overwrote variable str

-> str.substring(str.indexOf("start")+1, str.indexOf("x|y"))
|  java.lang.StringIndexOutOfBoundsException thrown: begin 1, end -1, length 14
|        at String.checkBoundsBeginEnd (String.java:3119)
|        at String.substring (String.java:1907)
|        at (#98:1)
© www.soinside.com 2019 - 2024. All rights reserved.