[英]Regex pattern to match string on the basis of “Starts with” and “Number of occurrences”
I need to find out only URLs those starts with http://www.example.com/blog/
and total number of character /
is exactly 5
. 我只需要找出以
http://www.example.com/blog/
开头的URL,而字符/
总数恰好是5
。
So it won't matches URL like 因此它不会与以下网址匹配
http://www.example.com/blog/category/cat-1/
http://www.example.com/blog/category/cat-2/
http://www.example.com/blog/tags/a-b-c/
It should only match URLs like 它只能匹配以下网址
http://www.example.com/blog/a-blog-title/
http://www.example.com/blog/another-blog-title/
http://www.example.com/blog/just-one-more-blog-title/
I have tried a lot on regxr but could not create one. 我在regxr上尝试了很多,但无法创建一个。
I will implement it in C# (if it makes any different). 我将在C#中实现它(如果有任何不同的话)。
Thanks in advance. 提前致谢。
You want something like: 您想要类似的东西:
bool isMatch = Regex.IsMatch(str, "^http://www.example.com/blog/[^/]*/[^/]*$");
(starts with your url, has 0-n characters, followed by a /, followed by 0-n characters, end of the string) (以您的网址开头,包含0-n个字符,后跟一个/,然后是0-n个字符,字符串的结尾)
这应该可以解决问题:
Regex reg = new Regex(@"^http://www.example.com/blog/[^/]*/[^/]*/$");
For this kind of task i'd use the Uri
class instead, for example (tested with a text file): 对于此类任务,我将改用
Uri
类,例如(使用文本文件进行测试):
Uri uri = null;
var uris = File.ReadLines(filePath)
.Where(l => Uri.TryCreate(l.Trim(), UriKind.Absolute, out uri))
.Select(l => uri);
var validUris = uris
.Where(u => u.Host == "www.example.com"
&& u.Segments.Length == 3
&& u.Segments[1] == "blog/");
You could try something like 您可以尝试类似
^http://(?=www.example.com/blog/)([^/]*/){3}$
Would match any url that starts with www.example.com/blog/
(after the http://
bit) and has a total of 5, two in the http://
and 3 in whatever comes after. 将匹配任何以
www.example.com/blog/
开头(在http://
位之后)且总共为5的http://
,其中两个在http://
,后面是3。
Not very well versed in C# so I'm not sure how to best apply the expression however. 不太熟悉C#,因此我不确定如何最好地应用该表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.