从带有正则表达式的字符串中获取title属性
本文关键字:获取 title 属性 字符串 正则表达式 | 更新日期: 2023-09-27 17:58:18
string asd = "<area href='#' title='name' shape='poly' coords='38,23,242'/>"
如何在c#中从标题中提取文本
然后在标题后面插入另一个空格?
搜索:(?<=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);
}
}
更新
要取出标题属性作为匹配,请使用以下选项:
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
试试这个:特别是你可能对HTMLAgilityPack的答案感兴趣。
Regex reg = new Regex("<a[^>]*?title='"([^'"]*?'"[^>]*?>");
几个问题:
这将匹配区分大小写,您可能需要调整
这需要title属性同时存在并被引用当然,如果title属性不存在,你可能无论如何都不想要匹配?
要提取,请使用组集合:
reg.Match("<a href='"#'" title='"Hello'">Howdy</a>").Groups[1].Value