【问题标题】:Regex to get only the text inside the double and Single quotes and the line number正则表达式仅获取双引号和单引号内的文本以及行号
【发布时间】:2013-05-10 21:58:02
【问题描述】:

正则表达式获取带有行号的双引号和单引号内的文本。

例如:

line 123 Processing File "This is what i am looking for"<'this is also what i need'>

输出应该是:

line 123 This is what i am looking for  this is also what i need

我的正则表达式是:

 MatchCollection matches2 = Regex.Matches(l, "\"([^\"]*)\"");

     foreach (Match match2 in matches2)
           {
                foreach (Capture capture2 in match2.Captures)
                    {
                        textBox4.Text = textBox4.Text + capture2.Value + Environment.NewLine;

                    }
            }

我得到(我的输出):

"This is what i am looking for"

我不需要双引号,我只需要引号内的文字。

【问题讨论】:

  • 不能用string.replace("\"","").replace("'","")去掉引号吗?

标签: c# regex


【解决方案1】:

这里的第一个问题是您正在查看匹配而不是捕获。捕获将向您显示 ( ) 运算符收集的内容。

matches2.OfType<Match>().Select(x => x.Captures[0].Value)

【讨论】:

  • 你能不能给出正则表达式模式来获取单引号和双引号。我怎样才能得到行号?谢谢
【解决方案2】:
string input =
    "line 123 Processing File \"This is what i am looking for\"<'this is also what i need'>";
string output =
    string.Join(" ", Regex.Matches(input, @"(line\s+(\d+)|(""|').*?\3)")
                          .Cast<Match>()
                          .Select(m => Regex.Replace(m.Value,
                                                     @"^[""']|[""']$", "")));

输出:

line 123 This is what i am looking for this is also what i need

【讨论】:

  • 它有效..但我也得到双引号后的文本..**第 283 行-//document."this text").style.display ="none ";** 我得到输出:-this text style.display=none 谢谢
  • 另一个简单的问题。什么是正则表达式来获取双引号中的文本。例如:“我需要这个”输出:-我需要这个。我得到:-“我需要这个”谢谢
  • 我没有得到这个结果。这个对我有用。示例中的第二个正则表达式删除了引号。
【解决方案3】:

试试这个:

Regex.Replace(inputtext, @"line (\d+).*?\""(.*?)""\W+(.*?)'", "line $1 $2 $3")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2011-05-01
    • 2013-10-20
    • 1970-01-01
    相关资源
    最近更新 更多