Reputation: 1763
I am trying to return part of a string, I want to return everything before the fist slash:
EC22941C/02/ORI
Should give me: EC22941C
I have used http://www.regexr.com/ to build up my expression:
(EC.+?)\/.+
When tested against my text:
EC22941C/02/ORI
It correctly tells me that the first group is
EC22941C
When I put it into C#:
public static string GetInstructionRef(string supplierReferenceId)
{
// The instruciton ref is the bit before the slash
var match = Regex.Match(supplierReferenceId, @"(EC.+?)\/.+");
if (match == null || match.Groups.Count == 0)
return "";
// Return the first group which is the instruction ref
return match.Groups[0].Value;
}
The result I get back is:
EC22941C/02/ORI
I have tried a number of different patterns and they all seem to do the same thing.
Does anyone have any idea what im doing wrong?
Upvotes: 0
Views: 61
Reputation: 70722
The issue is that you're returning the wrong group index, 0
will return the entire match while 1
returns the matched context of the capturing parentheses — numbered from left to right.
return match.Groups[1].Value;
Upvotes: 1
Reputation: 67968
^EC[^\/]+
You can simply use this and avoid using groups.See demo.
https://regex101.com/r/bW3aR1/6
string strRegex = @"^EC[^\/]+";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"EC22941C/02/ORI";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
Upvotes: 1
Reputation: 801
you should use match.Groups[1].Value
.
match.Groups[0].Value
returns the whole string (if it matches the pattern).
Also, you'd want to change your if condition as well. :)
Upvotes: 0