2

i write a piece of program to fetch content from a string between ":"(may not have) and "@" and order guaranteed,for example a string like "url:123@my.com",the I fetch "123",or "123@my.com" then i fetch "123" ,too; so I write a regular expression to implement it ,but i can not work,behind is first version:

Pattern pattern = Pattern.compile("(?<=:?).*?(?=@)");
Matcher matcher = pattern.matcher("sip:+8610086@dmcw.com");
if (matcher.find()) {
     Log.d("regex", matcher.group());
} else {
     Log.d("regex", "not match");
}

it can not work because in the first case:"url:123@my.com" it will get the result:"url:123" obviously not what i want:

so i write the second version:

Pattern pattern = Pattern.compile("(?<=:??).*?(?=@)");

but it get the error,somebody said java not support variable length in look behind;

so I try the third version:

Pattern pattern = Pattern.compile("(?<=:).*?(?=@)|.*?(?=@)");

and its result is same as the first version ,BUT SHOULD NOT THE FIRST CONDITION BE CONSIDERED FIRST?

it same as

Pattern pattern = Pattern.compile(".*?(?=@)|(?<=:).*?(?=@)");

not left to right! I consider I understood regular expression before ,but confused again.thanks in advance anyway.

4

3 回答 3

1

试试这个(稍微编辑,见评论):

String test = "sip:+8610086@dmcw.com";
String test2 = "8610086@dmcw.com";
Pattern pattern = Pattern.compile("(.+?:)?(.+?)(?=@)");
Matcher matcher = pattern.matcher(test);
if (matcher.find()) {
    System.out.println(matcher.group(2));
}
matcher = pattern.matcher(test2);
if (matcher.find()) {
    System.out.println(matcher.group(2));
}

输出:

+8610086
8610086

如果您需要有关模式的解释,请告诉我。

于 2013-05-29T08:45:36.690 回答
0

正如你所说,你不能在java中做一个变量lookbehind。

然后,你可以做这样的事情,你不需要lookbehind或lookaround。

正则表达式::?([^@:]*)@

示例在这个示例中(忘记 \n,它是因为 regex101),您将在第一组中获得您需要的内容,并且您不必做任何特别的事情。有时最简单的解决方案是最好的。

于 2013-05-29T08:46:50.460 回答
0

你真的不需要任何前瞻或后视。你需要的可以通过使用贪婪的量词和一些替代来完成:

    .*(?:^|:)([^@]+)

默认情况下,java 正则表达式量词 ( *+{n}?) 都是贪婪的(将匹配尽可能多的字符,直到找不到匹配项。可以通过在量词后使用问号使它们变得懒惰,如下所示:.*?

您将要为此表达式输出捕获组 1,输出捕获组 0 将返回整个匹配项。

于 2013-05-29T08:47:37.383 回答