Reputation: 5366
I want to pattern match this string
***** XXXXXXX 04/28/2017 14:48:40 *****
I want to get XXXXXXX
and 04/28/2017 14:48:40
.
So for I tried the regex
@"\*{5}(.*?)\*{5}"
which matches pattern but how to get the other two values.
Upvotes: 0
Views: 67
Reputation: 101
The following code will pull out each section as its own Group. A group is specified using the brackets around the regex group. You then can index each group as a dictionary with the position of the group in the string. 0 references the whole string that has matched with 1 being the first (*****) section and so on.
var str = "***** XXXXXXX 04/28/2017 14:48:40 *****";
var reg = new Regex(@"(\*{5})\s(.*?)\s([0-9/]*?)\s([0-9:]*?)\s(\*{5})", RegexOptions.Compiled);
var groups = reg.Match(str).Groups;
The use of the Lazy Quantifiers mean that each group will only match the minimum number of characters for the Regex to match. The \s will match any whitespace character for the string encoding.
The code above leaves us with the following matches in the groups variable:
0 > "***** XXXXXXX 04/28/2017 14:48:40 *****"
1 > "*****"
2 > "XXXXXXX"
3 > "04/28/2017"
4 > "14:48:40"
5 > "*****"
Upvotes: 1
Reputation: 2615
This expression will match
(X{7})|([042817/:])
= XXXXXXX 04/28/2017 14:48:40
This expression will match
(X{7})
= XXXXXXX
([042817/:])
= 04/28/2017 14:48:40
Upvotes: 1
Reputation: 3469
You don't need a regex since the stars and date are always going to be the same length it'll be very easy to extract the content, and in this case it wouldn't matter if the content has spaces or not
var a = "***** ABCDEFGEF 04/28/2017 14:48:40 *****";
var content = a.Substring(6, a.Length-32);
var datestring = a.Substring(a.Length-25).Replace("*","");
Console.WriteLine(content);
Console.WriteLine(datestring);
Output:
ABCDEFGEF
04/28/2017 14:48:40
In the content line of code you start at the last star and space then you go until the length of the string minus the date/time and stars (beginning and ending stars).
For the datestring you just start at the length of the date/time and stars.
Upvotes: 1