2

Using Java, I'm trying to write a regular expression that would parse another regular expression. I want to extract the named groups from the source regular expression (those represent parameters separated by slashes in an URL). Also, the source string may or may not start and end with a slash.

For example, for both source strings :

(?<name>john)/(?<facet>aaa/bbb/ccc/?)

and

/(?<name>john)/(?<facet>aaa/bbb/ccc/?)/

I'd like a regular expression that would extract those as named groups:

(?<name>john) and (?<facet>aaa/bbb/ccc/?)

I tried :

(^|.*/)(?<param>\(\?<[^>]+>[^\)]+\))(/.*|$)

But this only returns (?<name>john) as a group named "param", not (?<facet>aaa/bbb/ccc/?)!!

When I remove the (/.*|$) part, both are returned! But I want this ending condition to make sure a param is followed by a slash or is at the end of the line...

Do you have any idea why (/.*|$) prevents the second param to be found?

4

2 回答 2

1

环顾四周是你的朋友:(?=\/|\n)

这是您需要的一个小例子。例子

于 2012-12-01T20:20:31.530 回答
1

您可以使用以下正则表达式: -

"(?:/|^)(\\(\\?<.*?>.*?\\))(?=/|$)"

并使用Matcher@find方法提取所有匹配项。

String str = "(?<name>john)/***(?<facet>aaa/bbb/ccc/?)/(?<not>aaa/bbb/?)***";
Matcher matcher = Pattern.compile("(?:/|^)(\\(\\?<.*?>.*?\\))(?=/|$)").matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

输出 : -

(?<name>john)

最后一个不打印,因为它后面没有 aslash也没有end of line

于 2012-12-01T20:21:00.533 回答