我有一个
的字符串<a href="/KB/ajax/" id="ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL">Ajax</a>
现在我想在C#中使用Regex Class获取/ KB / ajax /和Ajax。
任何人都可以帮助我吗?
非常感谢
干杯
答案 0 :(得分:2)
string url = "<a href=\"/KB/ajax/\" id=\"ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL\">Ajax</a>";
Regex finder = new Regex("href=\"([^\"]*)\"");
string first = finder.Match(url).Groups[1].Value;
finder = new Regex(">([^<]*)<");
string second = finder.Match(url).Groups[1].Value;
答案 1 :(得分:0)
以下正则表达式还允许<a>...</a>
包含的文本内的标记:
<\s*a\b[^>] href\s*=\s*['"]([^"']*)['"][^>]*>((?:.(?!</a))*.)</a
C#.NET代码示例:
using System;
using System.Text.RegularExpressions;
namespace myapp
{
class Class1
{
static void Main(string[] args)
{
String sourcestring = "source string to match with pattern";
Regex re = new Regex(@"\<\s*a\b[^\>]+href\s*=\s*['""]([^""']*)['""][^\>]*\>((?:.(?!<\/a))*.)\<\/a");
MatchCollection mc = re.Matches(sourcestring);
int mIdx=0;
foreach (Match m in mc)
{
for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
{
Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
}
mIdx++;
}
}
}
}
$匹配数组:
(
[0] => Array
(
[0] => <a href="/KB/ajax/" id="ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL">Aj<b>a</b>x</a
)
[1] => Array
(
[0] => /KB/ajax/
)
[2] => Array
(
[0] => Aj<b>a</b>x
)
)