java 如何在android中为此创建正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1129996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create a regular expression for this in android?
提问by Rahul Vyas
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.
现在我想创建一个正则表达式来匹配 Ka 在空格后出现的位置,并且还想获取匹配字符的索引。
I am using java language.
我正在使用java语言。
回答by Josef Pfleger
You can use regular expressions just like in Java SE:
您可以像在 Java SE 中一样使用正则表达式:
Pattern pattern = Pattern.compile(".* (Ka).*");
Matcher matcher = pattern.matcher("Manoj Kumar Kashyap");
if(matcher.matches())
{
int idx = matcher.start(1);
}
回答by Daniel Sloof
You don't need a regular expression to do that. I'm not a Java expert, but according to the Android docs:
你不需要正则表达式来做到这一点。我不是 Java 专家,但根据Android 文档:
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.
public int indexOf (String string)
在此字符串中搜索指定字符串的第一个索引。对字符串的搜索从开头开始并移向该字符串的结尾。参数
string 要查找的字符串。返回
此字符串中指定字符串的第一个字符的索引,如果指定字符串不是子字符串,则返回 -1。
You'll probably end up with something like:
你可能会得到类似的结果:
int index = somestring.indexOf(" Ka");
回答by Harry Lime
If you really need regular expressions and not just indexOf, it's possible to do it like this
如果您真的需要正则表达式而不仅仅是indexOf,可以这样做
String[] split = "Manoj Kumar Kashyap".split("\sKa");
if (split.length > 0)
{
// there was at least one match
int startIndex = split[0].length() + 1;
}

