Reputation: 57
only after at least 3 characters and only one of those characters should be matched e.g.
for lumia820
the match should be a8
but for aa6
there should not be any match.
My current attempt is /([a-z]{3,})([0-9])/
, however this wrongly includes the leading characters. This is probably an easy one for regex specialists but I am completely stuck here.. Can someone pls help?
Upvotes: 2
Views: 6798
Reputation: 270609
If you need at least 3, you can use {2,}
to match 2 or more, and then capture the following character along with the next digit:
/[a-z]{2,}([a-z][\d])[\d]*/
[a-z]{2,}
matches at least 2 characters at the start. This ensures there are 2 or more characters before the one you capture.([a-z][\d])
captures the next character followed by the first digit[\d]*
matches any remaining trailing digits.If this must be anchored, don't forget ^$
.
/^[a-z]{2,}([a-z][\d])[\d]*$/
// Matching example aabc9876 yields c9
"a string with aabc9876 and other stuff".match(/[a-z]{2,}([a-z][\d])[\d]*/)
// ["aabc9876", "c9"]
// Non-matching example with zx8
"a string with zx8 should not match".match(/[a-z]{2,}([a-z][\d])[\d]*/)
// null
Upvotes: 2
Reputation: 8818
Assuming you're in an environment that allows lookbehinds, you could do this:
/(?<=[a-z]{2,})([a-z][0-9])/
That will look for two or more letters right before what we want to capture, make sure that they're there without including them in the capture group, and then capture the third (or more) letter followed by the number. The capture itself will make sure that the third letter is there.
@HolyMac per your comment:
Note that I am using c#, and I'm not sure of the differences with Objective-C, but the following matches f9
for me:
string testString = "abasfsdf9314";
Regex regex = new Regex("(?<=[a-z]{2,})([a-z][0-9])");
Match match = regex.Match(testString);
Upvotes: 2