我必须检查这两个url是否匹配一个模式(或2,更准确)。如果是这样,我想提取部分数据。
1)/ selector / zh_ /any-string-chain-you-want.aspx?FamiId= 32
然后我需要将“en”和“32”提取到变量中。对我来说,正则表达式应该类似于/selector/ {0} /any -string-chain -you-want.aspx?Afami = {}}
2)/selector/en/F/32/any-string-chain-you-want.html
其中必须将en和32分配给变量。所以: /selector/{0}/F/{1}/any-string-chain-you-want.html
{0}:2个字母的语言代码,如en,fr,nl,es,... {1}:家庭ID整数(2或3个数字),如12,38,124等,但不是1212
关于如何实现它的任何想法?
提前致谢,
罗兰
答案 0 :(得分:1)
private const string Regex1 = @"/selector/(\w\w)/.+\.aspx?FamiId=(\d+)";
private const string Regex2 = @"/selector/(\w\w)/F/(\d+)/.+\.html";
Match m = Regex.Match(myString, Regex2);
string lang = m.Groups[1].Value;
string numericValue = m.Groups[2].Value;
答案 1 :(得分:1)
您应该在Regular Expressions上查看本教程。
您可以使用以下表达式:
\/selector\/([a-z]{2})\/.*\.aspx\?FamiId=([0-9]{2,3})
和
\/selector\/([a-z]{2})\/F\/([0-9]{2,3})\/.*\.html
答案 2 :(得分:1)
答案 3 :(得分:1)
这是正则表达式:
/selector/([a-z]{2})/.+?\.aspx\?FamiId=([0-9]+)
代码:
var regex = new Regex(@"/selector/([a-z]{2})/.+?\.aspx\?FamiId=([0-9]+)");
var test = "/selector/en/any-string-chain-you-want.aspx?FamiId=32";
foreach (Match match in regex.Matches(test))
{
var lang = match.Groups[1].Value;
var id = Convert.ToInt32(match.Groups[2].Value);
Console.WriteLine("lang: {0}, id: {1}", lang, id);
}
第二种情况的正则表达式:/selector/([a-z]{2})/F/([0-9]+)/.+?\.html
(代码不会改变)
答案 4 :(得分:1)
string str = @"/selector/en/any-string-chain-you-want.aspx?FamiId=32";
Match m = Regex.Match(str, @"/selector/(\w{2})/.+\.aspx\?FamiId=(\d{2,3})");
string result = String.Format(@"/selector/{0}/F/{1}/any-string-chain-you-want.html", m.Groups[1].Value, m.Groups[2].Value);
你去。
答案 5 :(得分:1)
您可以尝试:
^/.*?/(\w{2})/(?:F/|.*?FamiId=)(\d{2,3}).*$
适用于两个网址。
答案 6 :(得分:1)
你可以使用类似的东西
String urlSchema1= @"/selector/(<lang>\w\w)/.+\.aspx?FamiId=(<FamiId>\d+)";
Match mExprStatic = Regex.Match(inputString,urlSchema1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (mExprStatic.Success || !string.IsNullOrEmpty(mExprStatic.Value))
{
String language = mExprStatic.Groups["lang"].Value;
String FamId = mExprStatic.Groups["FamId"].Value;
}
String urlSchema2= @"/selector/(<lang>\w\w)/F/(<FamId>\d+)/.+\.html";
Match mExprStatic = Regex.Match(inputString,urlSchema2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (mExprStatic.Success || !string.IsNullOrEmpty(mExprStatic.Value))
{
String language = mExprStatic.Groups["lang"].Value;
String FamId = mExprStatic.Groups["FamId"].Value;
}