Reputation: 634
I have several strings that look like the following:
+H124005992014011/1527399999999I05Z
+H7039700000001/$99999999I051
+K122005962050171/120911234C117
I need each section to be split into its own variable. To do this i thought Regex would be the best way to go.
here are the rules for splitting.
I have the following Regex pattern which seems to match the strings fine but i am unsure how to turn this full pattern into a string and robust way of splitting these strings....
(^\+)(\D\d\d\d)(\w{1,13})(\d)(\/)(\d{5}|\$)(\w{0,13})\D\d\d\w$
I need to turn the above pattern into a form that will allow me to extract each of the matching sections screens.
Thanks in advance
Upvotes: 1
Views: 1996
Reputation: 37182
You will need to know about capturing groups. Basically, wrap each "group" that you care about in brackets. Then you can refer to the groups by their ordinal.
For using capturing groups in C#, see this question.
The regex you describe doesn't quite match your inputs though - see the following powershell script.
# Note, I have used **single-quotes**. This is VERY IMPORTANT!
# Powershell interprets a $ as a variable, unless it is inside single-quotes.
# This regex is as described in your comment
$regex = '^(\+)([a-zA-Z]\d{3})(\w{1,13})(\d)(/)(\d{5})(\w{0,13})([A-L]\d{2})(\w)$'
'+H124005992014011/1527399999999I05Z' -match $regex # TRUE
'+H7039700000001/$99999999I051' -match $regex # FALSE
'+K122005962050171/120911234C117' -match $regex # FALSE
# This regex matches all your sample input.
$regex = '^(\+)([a-zA-Z]\d{3})(\w{1,13})(\d)(/)([\d{5}|\$])(\w{0,13})([A-L]\d{2})(\w)$'
'+H124005992014011/1527399999999I05Z' -match $regex
'+H7039700000001/$99999999I051' -match $regex
'+K122005962050171/120911234C117' -match $regex
Using Powershell (which uses the same regex engine as C#, so is very suitable for fine-tuning your regex!), you can see the output.
Upvotes: 2