Reputation: 51
I need to find the matching result i.e a string using Regex. Let me demonstrate the scenario using sample inputs.
string input= "xb-cv_107_20190608_032214_006"; // <-1st case
string input = "yb-ha_107_20190608_032214_006__foobar"; // <-2nd case
string input= "fv_vgf_ka01mq3286__20190426_084135_039"; // <-3rd case
string input="fv_vgf_ka01mq3286__2090426_084135_039"; //<-4th case
For 1st case input, output required= "xb-cv_107_20190608_032214_006".
For 2nd case input, output required= "yb-ha_107_20190608_032214_006".
For 3rd case input, output required= "fv_vgf_ka01mq3286__20190426_084135_039".
For 4th case input, output required= null since the pattern does not match.
The procedure to get the output is:
_
followed by 8 decimals followed by '_'
followed by 6 decimals followed by 3 decimals_
followed by 8 decimals followed by _
followed by 6 decimals followed by 3 decimals exists followed by __
exists followed by anything random.Till now, I have come up with this Regex expression:
string pattern = @".+[_][0-9]{8}[_][0-9]{6}[_][0-9]{3}([_]{2})?";
var result = Regex.Match(input, pattern)?.Groups[0].Value ;
Upvotes: 0
Views: 63
Reputation: 626851
You may use
var result = Regex.Match(input, @"^(.+_[0-9]{8}_[0-9]{6}_[0-9]{3})__")?.Groups[1].Value;
Regex details:
^
- start of string(
- Group 1 start:
.+
- any 1+ chars other than LF, as many as possible_[0-9]{8}_[0-9]{6}_[0-9]{3}
- _
, 8 digits, _
, 6 digits, _
, 3 digits)
- end of Group 1__
- two underscores.If there is a match, the result
holds the value that resides in Group 1.
If there is no match, result
is null.
Upvotes: 3