从字符串中解析一个值

时间:2012-08-24 19:36:34

标签: c# regex

我正在谷歌搜索30分钟,但我找不到任何可以帮助我的东西。

我的问题是我正在尝试使用RegExp解析字符串中的某些内容。我通常是一个PHP开发人员,并会使用preg_match_all(),但由于这在C#中不存在(哦,真的),我还需要其他东西。

想象一下,我有这个字符串:

string test = "Hello this is a 'test' a cool test!";

现在我想得到单引号内的东西(') - 在本例中 test

先谢谢你的帮助。抱歉我的英语不好,这不是我的母语! :/

4 个答案:

答案 0 :(得分:2)

执行preg_match_all的C#方式是使用System.Text.RegularExpressions.Regex类和Match方法。

答案 1 :(得分:2)

这是一种更容易,非注册的方式:

string textInQuotes = String.Empty;
string[] split = test.Split('\'');
if (split.Length > 2) textInQuotes = split[1];

答案 2 :(得分:1)

以下是示例应用程序代码。

using System;
using System.Text.RegularExpressions;

namespace ExampleApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // This is your input string.
            string test = "Hello this is a 'test' a cool test!";
            // This is your RegEx pattern.
            string pattern = "(?<=').*?(?=')";

            // Get regex match object. You can also experiment with RegEx options.
            Match match = Regex.Match(test, pattern);
            // Print match value to console.
            Console.WriteLine(match.Value);
        }
    }
}

希望它能够结束!

答案 3 :(得分:1)

这是一个正则表达式解决方案,允许带有引用部分文本的转义分隔符。如果您更喜欢* nix反斜杠样式的转义,只需使用('')替换正则表达式的相应部分(\\')

static readonly Regex rxQuotedStringLiteralPattern = new Regex(@"
                 # A quoted string consists of
    '            # * a lead-in delimiter, followed by
    (?<content>  # * a named capturing group representing the quoted content
      (          #   which consists of either
        [^']     #   * an ordinary, non-delimiter character
      |          #   OR
        ('')     #   * an escape sequence representing an embedded delimiter
      )*         #   repeated zero or more times.
    )            # The quoted content is followed by 
    '            # * the lead-out delimiter
    "
    , RegexOptions.ExplicitCapture|RegexOptions.IgnorePatternWhitespace
    ) ;

public static IEnumerable<string> ParseQuotedLiteralsFromStringUsingRegularExpressions( string s )
{
  for ( Match m = rxQuotedStringLiteralPattern.Match( s ?? "" ) ; m.Success ; m = m.NextMatch() )
  {
    string raw    = m.Groups[ "content" ].Value ;
    string cooked = raw.Replace( "''" , "'" ) ;
    yield return cooked ;
  }
}