如何使用正则表达式提取字符串的这一部分

本文关键字:一部分 字符串 提取 何使用 正则表达式 | 更新日期: 2023-09-27 18:34:22

我有以下字符串

  var tabContents = {"1":"<div class='"ProductDetail'"><h2 class='"h2_style'" style='"margin: 0px 0px 15px; padding: 0px; border: 0px; vertical-align: baseline; font-weight: normal; color: rgb(0, 102, 153); letter-spacing: 0.3px; font-size: 16px; text-align: center; font-family: 'Lucida Grande', sans-serif; font-style: normal; font-variant: normal; line-height: 16px; orphans: auto; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webv><'/div>","2":"","3":"","4":""};

现在我想得到这部分

<div class='"ProductDetail'"><h2 class='"h2_style'" style='"margin: 0px 0px 15px; padding: 0px; border: 0px; vertical-align: baseline; font-weight: normal; color: rgb(0, 102, 153); letter-spacing: 0.3px; font-size: 16px; text-align: center; font-family: 'Lucida Grande', sans-serif; font-style: normal; font-variant: normal; line-height: 16px; orphans: auto; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webv><'/div>

所以这部分以"1":"开始,以","2"结束

如何获取这两个标记点之间的字符串?

C# .net 4.5

如何使用正则表达式提取字符串的这一部分

使用捕获组或环顾四周。

"1":"(.*?)","2"

使用上面的正则表达式并从组索引 1 中获取所需的字符串。

演示

(?<="1":").*?(?=","2")

使用上面的正则表达式并从组索引 0 中获取所需的字符串。

  • (?<="1":") 正面回头,断言比赛之前必须有"1":"

  • .*? 任何字符出现零次或多次的非贪婪匹配。

  • (?=","2") 积极的展望,断言比赛之后必须有","2"

演示

String input = @"var tabContents = {""1"":""<div class='""ProductDetail'""><h2 class='""h2_style'"" style='""margin: 0px 0px 15px; padding: 0px; border: 0px; vertical-align: baseline; font-weight: normal; color: rgb(0, 102, 153); letter-spacing: 0.3px; font-size: 16px; text-align: center; font-family: 'Lucida Grande', sans-serif; font-style: normal; font-variant: normal; line-height: 16px; orphans: auto; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webv><'/div>"",""2"":"""",""3"":"""",""4"":""""};";
Regex rgx = new Regex(@"""1"":""(.*?)"",""2""");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

输出:

<div class='"ProductDetail'"><h2 class='"h2_style'" style='"margin: 0px 0px 15px; padding: 0px; border: 0px; vertical-align: baseline; font-weight: normal; color: rgb(0, 102, 153); letter-spacing: 0.3px; font-size: 16px; text-align: center; font-family: 'Lucida Grande', sans-serif; font-style: normal; font-variant: normal; line-height: 16px; orphans: auto; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webv><'/div>

爱德酮