Is there any way to do a Regex Replace conditionally? Here's an example.
Say you have a number that you know corresponds to a phone, with no formatting:
5553331234
Formatted, it would be
(555)333-1234
However, we don't have the number formatted and want to apply formatting. You can do an easy regex match and capture each of the 3 groups with something along the following:
(\d{3})(\d{3})(\d{4})
From there, you can do a simple regex replace
($2)$3-$4
However, what if you might have an extension? Maybe you have more than the 10 standard phone digits:
555333123456789
Where 56789 would be an extension. In that case, I could match it with
(\d{3})(\d{3})(\d{4})(\d*)
If I want to format it, but only include the X for extension if it exists, can I do that? For instance, I could make my replace format:
($2)$3-$4x$5
However, if I did that, the x would show up even when there is no extension. Is there a way purely using the regex to make that x show up conditionally? Essentially it would be "if $5" exists or "if $5.Length() > 0".
As a workaround, I could include a named group in that regex match where (\d*) above becomes
(?<Conditional>\d*)
In the code, I could then assert the length of the group named "Conditional". However, I'd like to have a purely regex solution that does not require anything custom like that.