Reputation: 73
I have the following regex I use to find numeric pairs; [0-9][0-9]
If the string is even length, I get exactly what I want.
string x ="1234";
Regex.Matches(enc, @"[0-9][0-9]")
With the regex I get 12
,34
.
if I have string x="12345"
I get 12
,34
. How do I modify this if I want 23
,45
?
Upvotes: 1
Views: 1715
Reputation: 22817
This answer uses the input you entered in a comment below your question (see Results section for the inputs)
Since I'm not certain exactly what the outputs should be, I'll present you with the following 3 methods.
This method always ensures the pairs are matched from the end of the string.
\d{2}(?=(?:(?:\d{2})+|)(?:\D|$))
This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers
\d{2}(?=(?:\d{2})+\[|\[)
This method always ensures the pairs are matched from the end of the string only when a specific token follows the numbers and matches the remaining numbers normally (but also in pairs)
\d{2}(?=(?:\d{2})+\[|\[)|\d{2}(?=\d*$)
12345[FNC1]00112233
12345[FNC1]0011223
Method 1
23 45 00 11 22 33
23 45 01 12 23
Method 2
23 45
23 45
Method 3
23 45 00 11 22 33
23 45 00 11 22
\d{2}
Match any digit exactly twice(?=(?:\d{2})+\b|\b)
Positive lookahead ensuring either of the following matches
(?:\d{2})+\b
Match the following
(?:\d{2})+
Match the following one or more times
\d{2}
Match any digit exactly twice\b
Assert the position as a word boundary\b
Assert the position as a word boundarySame as Method 1's explanation, but instead of using \b
, it uses \[
to assert that the following character matches [
literally.
Same as Method 2's explanation, but adds |\d{2}(?=\d*$)
to the end.
|
acts like a boolean OR (match Method 2 or the following)\d{2}
Match any digit exactly twice(?=\d*$)
Positive lookahead ensuring what follows matches
\d*
Match any digit any number of times$
Assert position at the end of the lineUpvotes: 2
Reputation: 7292
Just do it like this:
([0-9]{2})+$
This will match all the pairs, unless you have an odd number of digits, in which case you'll match everything except the first digit. If you need the separate pairs, you can then just split the returned match into sequential pairs.
Live example: https://regex101.com/r/3gNoQd/4
Upvotes: 2