string asd = "<area href='#' title='name' shape='poly' coords='38,23,242'/>"
如何从c#
中的title属性中提取文本然后在标题后插入另一个属性?
答案 0 :(得分:1)
搜索:(?<=title=')[^']+
替换:something
演示:http://regex101.com/r/nR3vQ8
在你的情况下是这样的:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// This is the input string we are replacing parts from.
string input = "<area href='#' title='name' shape='poly' coords='38,23,242'/>";
// Use Regex.Replace to replace the pattern in the input.
// ... The pattern N.t indicates three letters, N, any character, and t.
string output = Regex.Replace(input, "(?<=title=')[^']+", "something");
// Write the output.
Console.WriteLine(input);
Console.WriteLine(output);
}
}
<强>更新强>
取出title属性作为匹配使用:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// First we see the input string.
string input = "<area href='#' title='name' shape='poly' coords='38,23,242'/>";
// Here we call Regex.Match.
Match match = Regex.Match(input, @"title='(\w+)'",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
}
}
输出
name
答案 1 :(得分:0)
试试这个:特别是你可能对HTMLAgilityPack答案感兴趣。
Regex reg = new Regex("<a[^>]*?title=\"([^\"]*?\"[^>]*?>");
一些问题:
这将匹配区分大小写,您可能需要调整
这期望title属性既存在又被引用 当然,如果title属性不存在,你可能还不想要这场比赛吗?
要提取,请使用groups集合:
reg.Match("<a href=\"#\" title=\"Hello\">Howdy</a>").Groups[1].Value