Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Match goups includes full string, how to exclude

Tags:

c#

regex

I have the following code;

var pattern = "(\".*\") (\".*\")";
var regex = Regex.Match(input, pattern);

The value for input would be similar to this;

"string part1" "string part2"

The regex groups include the following

groups[0] = "string part1" "string part2"
groups[1] = "string part1"
groups[2] = "string part2"

Is there a way to exclude groups[0] as I simply want to concatenate the strings while removing the " " between them so that it becomes;

"string part1string part2"

like image 233
ChrisBint Avatar asked Dec 05 '25 22:12

ChrisBint


1 Answers

Use LINQ .Skip(1) on the values you have in groups. Then, concat the rest of the items:

var input = "\"string part1\" \"string part2\"";
var pattern = "\"(.*)\" \"(.*)\"";
var match = Regex.Match(input, pattern);
if (match.Success) 
{
    Console.WriteLine("\"{0}\"",
        string.Join(
            " ",
            match.Groups
              .Cast<Group>()
              .Select(x=>x.Value)
              .Skip(1)
        )
    );
}

See the C# demo online.

Note I also moved the capturing group bounds inside the quotes to get rid of the quotation marks in the group values.

Also, consider an alternative pattern in case you want to match substrings between the closest quotes: var pattern = "\"([^\"]*)\" \"([^\"]*)\"";.

like image 55
Wiktor Stribiżew Avatar answered Dec 08 '25 12:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!