C# 在字符串中提取以某物开头和结尾的模式
我需要在字符串中提取一个以某物开头和结尾的模式 以下是网址: 在C#中,如何从该url提取模式C# 在字符串中提取以某物开头和结尾的模式,c#,regex,C#,Regex,我需要在字符串中提取一个以某物开头和结尾的模式 以下是网址: 在C#中,如何从该url提取模式%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9 模式的开始字符是%,结束字符是\u,您可以使用以下方法: string s = "http://monsite.com/articles/%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9_sto3955603/description.html"; Console.Wri
%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9
模式的开始字符是%
,结束字符是\u
,您可以使用以下方法:
string s = "http://monsite.com/articles/%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9_sto3955603/description.html";
Console.WriteLine(s.Substring(s.IndexOf('%'), s.IndexOf('_' ) - s.IndexOf('%') + 1));
输出将是
%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9_
这里有一个
如果您想首先检查字符串是否有%
或\uu
字符,可以使用以下方法:
if(s.Contains("%") && s.Contains("_") && (s.IndexOf('_') > s.IndexOf('%')))
{
// Your string has % and _ characters and also _ comes after first %.
}
考虑以下代码段 输出是 %d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9_
但是哪个
%
字符?第一个?如果你解码的话,从这个url中提取一个模式可能会容易得多var decoded=System.Web.HttpUtility.UrlDecode(url)如果字符串中确实有一个'%'
和一个'.
,则code>将起作用。
string input = "http://monsite.com/articles/%d8%a7%d8%af%d9%85%d9%8a%d9%84%d8%b3%d9%88%d9_sto3955603/description.html";
var output = Regex.Match(input, @"%[\w\d%]*_");
Console.WriteLine(output.Value);