【问题标题】:How do I create a regular expression for this in android?如何在android中为此创建正则表达式?
【发布时间】:2009-07-15 07:50:21
【问题描述】:

假设我有一个这样的字符串:

string = "Manoj Kumar Kashyap";

现在我想创建一个正则表达式来匹配 Ka 出现在空格之后的位置,并且还想获取匹配字符的索引。

我正在使用java语言。

【问题讨论】:

    标签: java android regex


    【解决方案1】:

    您可以像在 Java SE 中一样使用正则表达式:

    Pattern pattern = Pattern.compile(".* (Ka).*");
    Matcher matcher = pattern.matcher("Manoj Kumar Kashyap");
    if(matcher.matches())
    {
        int idx = matcher.start(1);
    }

    【讨论】:

      【解决方案2】:

      您不需要正则表达式来执行此操作。我不是Java专家,但根据Android docs

      public int indexOf(字符串字符串)
      在此字符串中搜索第一个 指定字符串的索引。这 搜索字符串从 开始并移向结束 这个字符串。

      参数
      要查找的字符串。

      返回
      第一个的索引 中指定字符串的字符 此字符串,如果指定,则为 -1 字符串不是子字符串。

      你可能会得到类似的结果:

      int index = somestring.indexOf(" Ka");
      

      【讨论】:

        【解决方案3】:

        如果你真的需要正则表达式而不仅仅是indexOf,可以这样做

        String[] split = "Manoj Kumar Kashyap".split("\\sKa");
        if (split.length > 0)
        {
            // there was at least one match
            int startIndex = split[0].length() + 1;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-07-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-30
          • 2015-04-19
          相关资源
          最近更新 更多