Sha*_*arg 1 java regex string indexof
我正在寻找一种优雅的方法来找到一组分隔符之一的第一个外观.
例如,假设我的分隔符集由{";",")","/"}.
如果我的字符串是
"aaa/bbb;ccc)"
我想得到结果3(索引"/",因为它是第一个出现).
如果我的字符串是
"aa;bbbb/"
我想得到结果2(索引";",因为它是第一个出现).
等等.
如果String不包含任何分隔符,我想返回-1.
我知道我可以通过首先找到每个分隔符的索引,然后计算索引的最小值,忽略它们来做到这一点-1.这段代码变得非常麻烦.我正在寻找一种更短,更通用的方式.
通过正则表达式,它会像这样完成,
String s = "aa;bbbb/";
Matcher m = Pattern.compile("[;/)]").matcher(s); // [;/)] would match a forward slash or semicolon or closing bracket.
if(m.find()) // if there is a match found, note that it would find only the first match because we used `if` condition not `while` loop.
{
System.out.println(m.start()); // print the index where the match starts.
}
else
{
System.out.println("-1"); // else print -1
}
Run Code Online (Sandbox Code Playgroud)