Got some great help from this post answer a while back here
Now I'm trying take that and capture a couple patterns in my multi-line string but not working. Any hints for me?
Here's a .net fiddle I'm playing with
desired result:
//these can be letters
1: 3333
2: 1111
code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var item = " john smith (ABCDEFG) <[email protected]>\n"
"target1 = 3333, j\n"
"target2 1111, ";
String[] patternArr = {"(?:\\s*)",
"(?<target1>target1 = (\\w )])", // capture the first target
"(?:\\s*)",
"(?<target2>target2 (\\w ))", // captures the second target
};
var pattern = String.Join("", patternArr);
var m = Regex.Match(item, pattern);
if (m.Success)
{
Console.WriteLine("target1: {0}", m.Groups["target1"]);
Console.WriteLine("target2: {0}", m.Groups["target2"]);
}
}
}
CodePudding user response:
You can use
var pattern = @"target1 = (?<target1>\w ).*\ntarget2\s (?<target2>\w )";
See the regex demo. Regex details:
target1 =
- a literal string(?<target1>\w )
- Group "target1": one or more word chars.*
- the rest of the line\n
- the newline chartarget2
- literal string\s
- one or more whitespaces(?<target2>\w )
- Group "target2": one or more word chars
See the C# demo:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var item = " john smith (ABCDEFG) <[email protected]>\n"
"target1 = 3333, j\n"
"target2 1111, ";
var pattern = @"target1 = (?<target1>\w ).*\ntarget2\s (?<target2>\w )";
var m = Regex.Match(item, pattern);
if (m.Success)
{
Console.WriteLine("target1: {0}", m.Groups["target1"]);
Console.WriteLine("target2: {0}", m.Groups["target2"]);
}
}
}
Output:
target1: 3333
target2: 1111