0

我正在尝试使用正则表达式从撇号之间的字符串中获取子字符串。字符串格式:Duplicate entry 'bla@bla.bl' for key 'email'. 我正在使用的正则表达式:'([^']*).

代码:

Pattern pattern = Pattern.compile("'([^']*)");
Matcher matcher = pattern.matcher(duplicated);
Log.d(TAG, matcher.group()));

我也不确定matcher.group(),它返回一个与整个正则表达式匹配的字符串。就我而言,它应该返回两个子字符串。

有人可以纠正这个正则表达式并给我一个解释吗?提前致谢

4

4 回答 4

2

更好地使用.split()而不是模式匹配。它只是硬编码。执行以下操作:

String[] strSplitted = <Your String>.split("`");

然后,strSplitted 数组包含在 `.

于 2013-06-25T11:20:39.697 回答
1

Here's my tested solution. You have to call find

Pattern pattern = Pattern.compile("'([^']*)'");
String duplicated = "Duplicate entry 'bla@bla.bl' for key 'email'";
Matcher matcher = pattern.matcher(duplicated);

String a = "";
while (matcher.find()) {
    a += matcher.group(1) + "\n";
}

Result:

bla@bla.bl
email
于 2013-06-25T11:44:08.980 回答
1

我发明了我的解决方案,如下所示。

int second_index = 0;
String str = "Duplicate entry 'bla@bla.bl' for key 'email'";
while (true) {
    if (second_index == 0)
        first_index = str.indexOf("'", second_index);
    else
        first_index = str.indexOf("'", second_index + 1);

    if (first_index == -1)
        break;

    second_index = str.indexOf("'", first_index + 1);

    if (second_index == -1)
        break;

    String temp = str.substring(first_index + 1, second_index);

    Log.d("TAG",temp);
}

输出

06-25 17:25:17.689: bla@bla.bl
06-25 17:25:17.689: 电子邮件

于 2013-06-25T11:48:32.590 回答
1

我会使用这个正则表达式。它几乎和你的一模一样,但我包括了结束单引号。这是为了防止在下一场比赛中使用结束单引号。

'([^']*)'

要获取单引号内的内容,请使用类似于以下的行:

matcher.group(1)

这是一个 Java 示例:

Pattern regex = Pattern.compile("'([^']*)'", Pattern.MULTILINE);
Matcher matcher = regex.matcher(duplicated);
while (matcher.find()) {
    Log.d(TAG, matcher.group(1)));
} 
于 2013-06-25T11:30:01.850 回答