开发者

How to do regex match in a string with quotes in C#

Given the string:

/home   "1020....2010" main 

I would like home, 1020 and 2010 using regex, but keep having problems with the quote. Can anyone help me out?


Thank you guys for your post. I realize that my code might 开发者_运维技巧have some problem. Here it is

string pattern[1] = @"blablabla"; string pattern[2] = @"blablabla"; ......

foreach (string s in pattern) { if (regex.match(line, s).success) { ...... } }

Then there is error saying unexpected character "\"


Use the pattern:

/(\w+)\s+"(\d+)\.+(\d+)"

And home (or any other name after the /) will be in $1, the first number in $2 and the last number in $3.

EDIT 1

I thought the @ should work, but couldn't get it to compile in ideone.com. This does work however:

using System;
using System.Text.RegularExpressions;

public class RegexTest 
{
    public static void Main() 
    {
        Regex r = new Regex("/(\\w+)\\s+\"(\\d+)\\.+(\\d+)\""); 
        Match m = r.Match("/home   \"1020....2010\" main ");
        Console.WriteLine("$1 = " + m.Groups[1]);
        Console.WriteLine("$2 = " + m.Groups[2]);
        Console.WriteLine("$3 = " + m.Groups[3]);
    }
}

produces:

$1 = home
$2 = 1020
$3 = 2010

Test rig: http://ideone.com/TpQwf

EDIT 2

As @Seattle mentioned in the comments, when using the convenient @ before a regex-string, the double quotes needs to be escaped by placing a double quote in front of it (not a backslash!):

Regex r = new Regex(@"/(\w+)\s+""(\d+)\.+(\d+)"""); 


For the above, you want something like:

/(\w+) "(\d+)\.+(\d+)" (\w+)

Also check this:

  • Regex to match all except a string in quotes in C#


If you want to match a quote character (or other special characters), you can escape it using a backslash. So \" in your regex will match a " character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜