How to remove lone 1's if followed by any letter with Regex?

Viewed 82

Problem:

Input: 1b-12

Output: b-2

Desired output: b-12

Code I am currently using:

Regex.Replace("1b-12", @"\b1(\w+)\b", @"$1", RegexOptions.IgnoreCase);

Question:

How do I fix my regex to make 1b = b, but leave 11b as 11b and 11 as 11?

Thank you for any help.

1 Answers

Since \w matches letters, digits, underscores and some combining marks, you should use \p{L}, or - if you need to only allow ASCII letters - [a-zA-Z].

An example solution that matches 1 at the start of a word and then contains 1+ letters:

Regex.Replace("1b-12", @"\b1(?=\p{L}+\b)", "")
Regex.Replace("1b-12", @"\b1(?=[a-zA-Z]+\b)", "")

See the regex demo. Note you do not need RegexOptions.IgnoreCase as \p{L} and [a-zA-Z] match both lower and uppercase letters.

Details

  • \b - here, a start of a word
  • 1 - a 1 char
  • (?=\p{L}+\b) - immediately followed with 1+ letters and then end of word. Also, as this is a lookahead pattern that does not consume chars, your replacement pattern can stay empty.
Related