Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在字符串中提取以某物开头和结尾的模式_C#_Regex - Fatal编程技术网

C# 在字符串中提取以某物开头和结尾的模式

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

我需要在字符串中提取一个以某物开头和结尾的模式

以下是网址:

在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.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);