9

Suppose I have a string like this:

string = "Manoj Kumar Kashyap";

Now I want to create a regular expression to match where Ka appears after space and also want to get index of matching characters.

I am using java language.

teedyay
  • 23,293
  • 19
  • 66
  • 73
Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256

3 Answers3

15

You can use regular expressions just like in Java SE:

Pattern pattern = Pattern.compile(".* (Ka).*");
Matcher matcher = pattern.matcher("Manoj Kumar Kashyap");
if(matcher.matches())
{
    int idx = matcher.start(1);
}
Josef Pfleger
  • 74,165
  • 16
  • 97
  • 99
4

You don't need a regular expression to do that. I'm not a Java expert, but according to the Android docs:

public int indexOf (String string)
Searches in this string for the first index of the specified string. The search for the string starts at the beginning and moves towards the end of this string.

Parameters
string the string to find.

Returns
the index of the first character of the specified string in this string, -1 if the specified string is not a substring.

You'll probably end up with something like:

int index = somestring.indexOf(" Ka");
Daniel Sloof
  • 12,568
  • 14
  • 72
  • 106
0

If you really need regular expressions and not just indexOf, it's possible to do it like this

String[] split = "Manoj Kumar Kashyap".split("\\sKa");
if (split.length > 0)
{
    // there was at least one match
    int startIndex = split[0].length() + 1;
}
Harry Lime
  • 29,476
  • 4
  • 31
  • 37