使用正则表达式提取部分内容

时间:2018-08-14 03:03:05

标签: regex

我正在尝试从 P‡GUID / CT-14-A2F2 / SU-14-1F939 中提取 14-A2F (匹配/ )或 P‡GUID / CT-14-A2F2 (在行尾匹配)

    final Pattern pattern = Pattern.compile("CT-[a-zA-Z0-9-\\-]+(/|\\z)");
    final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");

    matcher.find();
    matcher.group();

到目前为止没有成功,我的模式有问题吗,或者这不是matcher.group的用例

3 个答案:

答案 0 :(得分:1)

尝试使用正则表达式:(?<=CT-)[a-zA-Z0-9-\\]+(?=\/|$)

Demo

答案 1 :(得分:1)

在正则表达式CT-[a-zA-Z0-9-\\-]+(/|\\z)中,您匹配CT-[a-zA-Z0-9-\\-]+,然后对最后一部分使用捕获组,在这种情况下,它将捕获正斜杠。如果您使用matcher.group();,则会得到完整的匹配,CT-14-A2F2/

您可以将捕获组移到第一部分,然后在代码中引用第一个捕获组:

CT-([a-zA-Z0-9-\-]+)(?:/|\z)

在Java中:

CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)

final Pattern pattern = Pattern.compile("CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)");
final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");

matcher.find();
System.out.println(matcher.group(1)); // 14-A2F2

Demo

答案 2 :(得分:0)

此正则表达式将匹配两个正斜杠之间的所有内容。 从括号中删除该组。

/([^/]*)/

您不需要转义正斜杠

相关问题