如何使用Regex [duplicate]将所有匹配替换为另一种格式

mklgxw1f  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(109)

此问题已在此处有答案

Replace all occurrences of the Tab character within double quotes(2个答案)
关闭17天前。
下面我将html中包含的hrefs如下:

<a href="https://www.test.com/help">a</a><br/>
...
other html text
...
<a href="https://www.test.com/help2">b</a><br/>
...
other html text
...
<a href="https://www.test.com/help3">c</a>

如何使用Regex将href中的所有.字符替换为space字符?

<a href="https://www test com/help">a</a><br/>
<a href="https://www test com/help2">b</a><br/>
<a href="https://www test com/help3">c</a>

我正在尝试以下方法,但没有成功:

string textToHandle = "html text here";
string newUrl = string.Empty;
Regex rg = new Regex("(?<=(href=\"))[.\\s\\S]*?(?=(\"))", RegexOptions.IgnoreCase);

MatchCollection collection = rg.Matches(textToHandle);
foreach (Match match in collection)
{
    string u = match.Groups[0].Value;
    newUrl = rg.Replace(textToHandle, u.Replace(".", " "));
    Console.WriteLine(newUrl);
}

Console.WriteLine(newUrl);
fruv7luv

fruv7luv1#

为了将href属性中的所有.字符替换为空格,可以将正则表达式模式修改为(?<=href="")[^""]*(?=""),并使用MatchEvaluatorRegex.Replace()方法:

string textToHandle = "<a href=\"https://www.test.com/help3\">c</a>";
string newUrl = string.Empty;

// Updated regex pattern to match href values
string pattern = @"(?<=href="")[^""]*(?="")";
Regex rg = new Regex(pattern, RegexOptions.IgnoreCase);

// Match evaluator to replace '.' with ' '
MatchEvaluator evaluator = match => match.Value.Replace(".", " ");

// Replace all occurrences in the input text
newUrl = rg.Replace(textToHandle, evaluator);

Console.WriteLine(newUrl);
Console.ReadKey();

正则表达式解释

  • (?<=href="")正向后查找,以确保匹配在href="之前。
  • [^""]*匹配除"(双引号)以外的任何字符,零次或多次。
  • (?="")正向预测,以确保匹配后面是双引号"

相关问题