[Solved] Regex to remove leading 9 from a phone number, that isn’t at the start of the line [closed]


The following command should do what you want:

%s/^\d\{3} \zs9/

Note that this will only work if the phone numbers have the exact format you give. The regex is very specific, to make it a little more unlikely to screw up anything else in the file.


Since you said you were having trouble, I’ll explain what’s going on in this regex, so that even if you don’t decide to use it, you can at least learn a bit.

%s means “do the substitution on every line.” This isn’t really part of the regex. It’s a standard vim command.

^ is an anchor, meaning “this must be the location of the start of the line” – or, in other words, “nothing may precede the following stuff on the line.”

\d\{3} means “there must be exactly three digits here,” which means that the first three characters of the line must be digits.

(space) means there must be a literal space next. Go figure.

\zs means “actually start the match here.” The stuff before must match, but don’t “select” anything previous.

9 means there must be a literal 9 next. This is what you’ll match.

/, the last character, means “everything next is what you should replace the match with.” Since nothing follows it, it means “replace the match with nothing.”

Done!

Edit:

Apparently, the data file in question did not have exactly one space between the first group of digits and the second. To account for this, change the part of the regex that affects the match on the whitespace.

Thus, the space in the regex should be replaced by \s\+, meaning “match any whitespace character one or more times.” So, the regex would be:

%s/^\d\{3}\s\+\zs9/

6

solved Regex to remove leading 9 from a phone number, that isn’t at the start of the line [closed]