开发者

Matching a string with and without quotes with Regex

Hey all, I know there are a lot of questions out there f开发者_如何学Goor matching quotes with Regex but the few I tried haven't gotten me far yet... I think its just a case of being new to Regex

Basically I'm parsing a unix grep command string and need to pull out all the grep'ed stuff. An example:

cat theLogFile | grep "some stuff" | grep moreStuffWithRandomChars*&^^#&@_+ | grep "stuff" | grep thing2

and I would like the results to be:

"some stuff"
moreStuffWithRandomChars*&^^#&@_+
"stuff"
thing2

Thanks all!


this pattern returns the results below as the first group

string regexPattern = @"grep (.*?)( \||$)";

"some stuff"

moreStuffWithRandomChars*&^^#&@_+

"stuff"

thing2

Here is an example of how to use it:

try 
{
    Regex regex = new Regex(@"grep (.*?)( \||$)");
    Match grepStrings = regex.Match(commandline);
    while (grepStrings.Success) 
    {
        // matched text: grepStrings.Value
        // match start: grepStrings.Index
        // match length: grepStrings.Length
        grepStrings = grepStrings.NextMatch();
    } 
} 
catch (ArgumentException ex)
{
    // Syntax error in the regular expression
}


I don't know if this addresses all your needs, but here's a pointer: you can split the string like this:

Regex.Split(string, "| grep ")

and then throw away the first part.


Do you need to use regular expressions? Why not just do this?

var cmdStr = @"cat theLogFile | grep ""some stuff"" | grep moreStuffWithRandomChars*&^^#&@_+ | grep ""stuff"" | grep thing2";
var results = cmdStr.Split('|')
                    .Select(s => s.Trim())
                    .Where(s => s.StartsWith("grep ", StringComparison.OrdinalIgnoreCase))
                    .Select(s=> s.Substring(5))
                    .ToList();
// { "some stuff", moreStuffWithRandomChars*&^^#&@_+, "stuff", thing2 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜