【问题标题】:How to get indexOf multiple delimiters?如何获取 indexOf 多个分隔符?
【发布时间】:2015-04-06 06:11:46
【问题描述】:

我正在寻找一种优雅的方式来查找一组分隔符中的一个的第一次出现。

例如,假设我的分隔符集由 {";",")","/"} 组成。

如果我的字符串是
"aaa/bbb;ccc)"
我想得到结果 3("/" 的索引,因为它是第一个出现的)。

如果我的字符串是
"aa;bbbb/"
我想得到结果 2(";" 的索引,因为它是第一个出现的)。

等等。

如果字符串不包含任何分隔符,我想返回-1

我知道我可以通过首先找到每个分隔符的索引,然后计算索引的最小值,忽略 -1 来做到这一点。这段代码变得非常繁琐。我正在寻找一种更短更通用的方式。

【问题讨论】:

  • 与其尝试逐个查找每个分隔符,不如遍历字符串的字符并测试每个字符是否是分隔符之一会更有效。或者你可以使用正则表达式。

标签: java regex string indexof


【解决方案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
}

【讨论】:

    【解决方案2】:

    在分隔符列表中搜索输入字符串中的每个字符。如果找到,则打印索引。 也可以使用Set来存储分隔符

    【讨论】:

      【解决方案3】:

      下面的程序会给出结果。这是使用 RegEx 完成的。

        import java.util.regex.Matcher;
      import java.util.regex.Pattern;
      
      public class FindIndexUsingRegex {
      
      /**
       * @param args
       */
      public static void main(String[] args) {
          // TODO Auto-generated method stub
          findMatches("aaa/bbb;ccc\\)",";|,|\\)|/");
      }
      
      public static void findMatches(String source, String regex) {
          Pattern pattern = Pattern.compile(regex);
          Matcher matcher = pattern.matcher(source);
      
          while (matcher.find()) {
              System.out.print("First index: " + matcher.start()+"\n");
              System.out.print("Last index: " + matcher.end()+"\n");
              System.out.println("Delimiter: " + matcher.group()+"\n");
              break;
          }
      }
      
      }
      

      输出:

         First index: 3
      Last index: 4
      Delimiter: /
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-22
        • 1970-01-01
        • 2012-05-20
        • 2022-01-20
        • 1970-01-01
        • 2021-09-25
        • 1970-01-01
        相关资源
        最近更新 更多