路径的正则表达式问题

时间:2014-04-13 16:11:31

标签: c# regex

我使用以下正则表达式@"^(.+)/([^/]+)$",我需要检查 如果它的路径包含alfanumeric,如斜杠
目前它正在工作 但是如果我像 aaa / bbb / 那样,我得到了错误,因为我有 bbb 之后的最后一条路径。我该如何解决?

1 个答案:

答案 0 :(得分:1)

Regex

^(.*)\/([^\/]+)(\/)?$

Regular expression visualization

Debuggex Demo

<强>描述

^ assert position at start of the string
1st Capturing group (.*)
    .* matches any character (except newline)
        Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    \/ matches the character / literally
2nd Capturing group ([^\/]+)
    [^\/]+ match a single character not present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    \/ matches the character / literally
3rd Capturing group (\/)?
    Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
    Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
    \/ matches the character / literally
$ assert position at end of the string

C#代码

string pattern = "^(.+)\/([^\/]+)(\/)?$";

Alphanumeric Regex

^(\w*)\/(\w*)(\/)?$

Regular expression visualization

Debuggex Demo