简体   繁体   中英

Parse a value from a string

I was googling for 30 minutes but I didn't find anything that could help me.

My problem is that I'm trying to parse something from a string with RegExp. I'm normally a PHP developer and would use preg_match_all() for it, but since this doesn't exists in C# (oh really), I need something else.

Imagine I have this string:

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

Now I want to get the thing that is inside single quotes ( ' ) - in this example test .

Thanks in advance for helping me. Sorry for my bad English, it's not my native language! :/

C#进行preg_match_all是使用System.Text.RegularExpressions.Regex类,然后使用Match方法。

An easier, non reg-ex way of doing this:

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

Here's the example application code.

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);
        }
    }
}

Hope it hepls!

Here's a regex solution that allows for escaped delimiters withing the quoted portion of the text. If you prefer the *nix backslash style of escapes, simply replace the appropriate part of the Regex, ('') , with (\\\\') .

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 ;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM