I have a list of strings with the output below
stop = F6, quantity ( 1 ) // stop 0
stop = F8, quantity ( 1 ) // stop 1
stop = BN, quantity ( 1 ) // stop 2
stop = F6, quantity ( 1 ) // stop 3
stop = F8, quantity ( 1 ) // stop 4
stop = BN, quantity ( 1 ) // stop 5
stop = F6, quantity ( 1 ) // stop 6
stop = F8, quantity ( 1 ) // stop 7
stop = SC, quantity ( 1 ) // stop 8
etc
using a foreach loop i'm retrieving each line in the list ie
`stop = F6, quantity ( 1 ) // stop 0`
However I only need the character F6. I Know I need to use regex to retrieve f6 in this instance, however, I am unsure on the expression. From a brief tutorial on regex, I've tried using the code below to achieve this with no luck
`Regex.Match(output, @"=\w*,").Value.Replace("\"", "");`
Any help would be appreciated.
You can use this pattern:
"=\\s([A-Za-z0-9]{2}),"
//or
"=\\s(\\w+),"
Code:
string str = "stop = F6, quantity ( 1 ) ";
var res = Regex.Matches(str, "=\\s([A-Za-z0-9]{2}),")[0].Groups[1].Value;
i don't know much in C# but you're regex is this : "= (\\w+),"
. That regex get any words/digit between =
and ,
.
In regex, an expression between parenthesis is call a "Capturing Group". In any languages you have some API to retrieve content capture in capturing group. I found this for C# : https://msdn.microsoft.com/fr-fr/library/system.text.regularexpressions.match.groups(v=vs.110).aspx
So the code for retrieve you're data look like that :
String pattern = @"=\\s(\\w+),";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("Value : {0}", match.Groups[1].Value);
}
To test you're regex in live, https://regex101.com/ is so usefull ! Use it to see visually what the regex request do while you write it.
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.