正则表达式匹配路径的一部分

时间:2018-10-11 21:59:04

标签: regex

我正在寻找正则表达式,该正则表达式与example/之后的所有内容匹配,直到字符串的末尾或直到下一个斜杠为止。

  1. example / matchingrandomtext12345
  2. example / matchingrandomtext12345 /
  3. example / matchingrandomtext12345 / moretext

所有3个示例都应与matchingrandomtext12345相匹配,并且正则表达式不应使用正向后视。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我不知道您使用的是哪种语言,但是您应该使用以下表达式:example/(.*?)(/|$)并与第1组匹配,请检查Java中的以下代码段,它完全返回您想要的内容...

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex3 {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("example/(.*?)(/|$)");

        List<String> entries = Arrays.asList(
            "example/matchingrandomtext12345", 
            "example/matchingrandomtext12345/", 
            "example/matchingrandomtext12345/moretext"
        );

        for (String entry : entries) {
            Matcher matcher = pattern.matcher(entry);
            matcher.find();
            System.out.println(matcher.group(1));
        }
    }
}

它返回输出:

matchingrandomtext12345
matchingrandomtext12345
matchingrandomtext12345

希望我有所帮助!