【问题标题】:Creating a regular expression in C# [closed]在 C# 中创建正则表达式 [关闭]
【发布时间】:2019-09-16 17:53:57
【问题描述】:

我从查询中得到 3 种字符串:

**TYPE1 :**["type1"]
**TYPE2 :**["type2 type2 type2"]
**TYPE3 :**["type3 type3"]

我写了一个代码来只提取单词或句子,但是代码给出了错误,请纠正我在代码中的错误。

// error in regular expression
Regex _regex = new Regex(@"\"\w.+\"");
Match _match = _regex.Match(temp);
if (_match.Success)
{
    resourceAnalyticsModel.ResourceFieldName = _match.Value;
}

【问题讨论】:

  • 抛出了哪个错误?
  • 我将其命名为 "\"type3 type3\"" 但我想要 "type3 type3"
  • 现在呢?它会引发错误还是得到错误的结果?准确!

标签: c# regex asp.net-mvc


【解决方案1】:

尝试以下:

            string[] inputs = { "**[\"type1\"]", "**[\"type2 type2 type2\"]", "**[\"type3 type3\"]" };

            foreach (string input in inputs)
            {
                Regex _regex = new Regex("\"([^\"]+)");
                Match _match = _regex.Match(input);
                Console.WriteLine(_match.Groups[1].Value);
            }

【讨论】:

  • 当前结果:"type2 type2 type2 预期结果:type2 type2 type2
  • 代码给出了预期的结果。不知道你做错了什么。
【解决方案2】:

当您使用文字字符串(字符串前的@)时,您必须通过双引号转义引号,因此您的模式应该是:

Regex _regex = new Regex(@"""\w.+""");

或者,如果您不想使用文字字符串:

Regex _regex = new Regex("\"\\w.+\"");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多