Reputation: 640
I am new to RegEx and thus have a question on RegEx. I am writing my code in C# and need to come up with a regex to find matching strings.
The possible combination of strings i get are,
XYZF44DT508755
ABZF44DT508755
PQZF44DT508755
So what i need to check is whether the string starts with XY or AB or PQ.
I came up with this one and it doesn't work.
^((XY|AB|PQ).){2}
Note: I don't want to use regular string StartsWith()
UPDATE:
Now if i want to try a new matching condition like this -
If string starts with "XY" or "AB" or "PQ" and 3rd character is "Z" and 4th character is "F"
How to write the RegEx for that?
Upvotes: 0
Views: 829
Reputation: 70732
You can modify you expression to the following and use the IsMatch()
method.
Regex.IsMatch(input, "^(?:XY|AB|PQ)")
The outer capturing group in conjuction with .
(any single character) is trying to match a third character and then repeat the sequence twice because of the range quantifier {2}
...
According to your updated edit, you can simply place "ZF" after the grouping construct.
Regex.IsMatch(input, "^(?:XY|AB|PQ)ZF")
Upvotes: 3
Reputation: 9647
You were on the right track. ^(XY|AB|PQ)
should match your string correctly.
The problem with ^((XY|AB|PQ).){2}
is following the entire group with {2}
. This means exactly 2 occurrences. That would be 2 occurrences of your first 2 characters, plus .
(any single character), meaning this would match strings like XY_AB_
. The _
could be anything.
It may have been your intention with the .
to match a larger string. In this case you might try something along the lines of ^((XY|AB|PQ)\w*)
. The \w*
will match 0 or more occurrences of "word characters", so this should match all of XYZF44DT508755
up to a space, line break, punctuation, etc., and not just the XY
at the beginning.
There are some good tools out there for understanding regexes, one of my favorites is debuggex.
To answer your updated question:
If string starts with "XY" or "AB" or "PQ" and 3rd character is "Z" and 4th character is "F"
The regex would be (assuming you want to match the entire "word"). ^((XY|AB|PQ)ZF\w*)
Upvotes: 1
Reputation: 3422
You want to test for just ^(XY|AB|PQ)
. Your RegEx means: Search for either XY, AB or PQ, then a random character, and repeat the whole sequence twice, for example "XYKPQL" would match your RegEx.
This is a screenshot of the matches on regex101:
^
forces the start of line,
(...)
creates a matching group and
XY|AB|PQ
matches either XY, AB or PQ.
If you want the next two characters to be ZF, just append ZF to the RegEx so it becomes ^(XY|AB|PQ)ZF
.
Check out regex101, a great way to test your RegExes.
Upvotes: 2