c# - Regex that removes the 2 trailing letters from a string not preceded with other letters -
this in c#. i've been bugging head not luck far.
so example
123456bvc --> 123456bvc (keep same) 123456bv --> 123456 (remove trailing letters) 12345v -- > 12345v (keep same) 12345 --> 12345 (keep same) abc123ab --> abc123 (remove trailing letters)
it can start anything.
i've tried @".*[a-za-z]{2}$"
no luck
this in c# return string removing 2 trailing letters if exist , not preceded letter.
match result = regex.match(mystring, pattern); return result.value;
your @".*[a-za-z]{2}$"
regex matches 0+ characters other newline (as many possible) , 2 ascii letters @ end of string. not check context, 2 letters matched regardless of comes before them.
you need regex match last 2 letters not preceded letter:
(?<!\p{l})\p{l}{2}$
see this regex demo.
details:
(?<!\p{l})
- fails match if letter (\p{l}
) found before current position (you may use[a-za-z]
if want deal ascii letters)\p{l}{2}
- 2 letters$
- end of string.
in c#, use
var result = regex.replace(mystring, @"(?<!\p{l})\p{l}{2}$", string.empty);
Comments
Post a Comment