String.substring()OR运算符

时间:2018-03-04 01:24:47

标签: java string indexing

是否可以在substring内执行OR运算符?这是我的,但它没有工作

str.substring(str.indexOf("start")+1, str.indexOf("x|y"))

2 个答案:

答案 0 :(得分:4)

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

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

Demo.

答案 1 :(得分:-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)