我正在学习Java中的正则表达式(技术上是Android API)并且遇到了一个问题。我最初使用的是Java String.matchAll(String expression, String occurence);
的基本功能,但现在我使用了Pattern和Matcher类。
我跟着this tutorial学习基础知识,看起来很简单。
我的Java正则表达式是info(.*?)\\,
,我也试过了:(?<=\\binfo\\=).*?(?=\\=)
。
对于第一个正则表达式,如果我有一个字符串"info i = 5,"
,它将解析为"info = 5"
。对于第二个,如果使用相同的字符串,我会得到一个没有匹配的例子(我认为是InputMismatchException)。
我的解析代码是:
//Produces "info i 5" rather than the desired "i"
public String parseStringAlias(String textToBeParsed)
{
//Gets the value(or alias) located between the word info and the = sign
Pattern p = Pattern.compile("info(.*?)\\=");
Matcher m = p.matcher(textToBeParsed);
//0 would be the first match
return m.group(0);
}
//Returns InputMismatchException rather than the desired number between equals sign and comma
//If given out example of "info i = 5," should return 5
public String parseStringValue(String textToBeParsed)
{
//Pattern fetches the value between the "=" and the ","
Pattern p = Pattern.compile("(?<==).*?(?=\\,)");
//Search for matches
Matcher m = p.matcher(textToBeParsed);
//0 would be the first match
return m.group(0);
}
答案 0 :(得分:2)
你的正则表达式存在一些问题:你应该只使用(
而不是{{)
转义特殊的正则表达式字符,例如[
,\\
,//
等。 1}}而不是像,
或=
这样的字符。
您没有匹配任何内容,因为您没有“运行”正则表达式搜索。
在每个返回行之前添加m.find()
,更好,在if
中使用它。看起来您正在使用.group(1)
方法寻找parseStringAlias
值:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(parseStringAlias("\"info i = 5,\""));
System.out.println(parseStringValue("\"info i = 5,\""));
}
//Produces "info i 5" rather than the desired "i"
public static String parseStringAlias(String textToBeParsed)
{
//Gets the value(or alias) located between the word info and the = sign
Pattern p = Pattern.compile("info(.*?)="); // <- Note removed `//`
Matcher m = p.matcher(textToBeParsed);
//0 would be the first match
if (m.find()) { // < - We "ran" the regex search
return m.group(1); // <- Group 1 is accessed
}
return "";
}
//Returns ImputMismatchException rather than the desired number between equals sign and comma
//If given out example of "info i = 5," should return 5
public static String parseStringValue(String textToBeParsed)
{
//Pattern fetches the value between the "=" and the ","
Pattern p = Pattern.compile("(?<==).*?(?=,)"); // <- Note removed `\\` and `//`
//Search for matches
Matcher m = p.matcher(textToBeParsed);
//0 would be the first match
if (m.find()) { // <- We "ran" the regex
return m.group(0); // <- We access 0th group, the whole match
}
return "";
}
请参阅IDEONE demo