I am using Sublime Text, and I was wondering if there is a way to do this with Regex:

I have multiple files that have different lines and text.

In each of them I have a line that starts with "NAME : " and continues with the name of the person:

NAME : john doe smith 

I am looking to use Regex to replace the spaces found in the text john doe smith with a character _, basically after the text NAME : , so the new line will be:

NAME : john_doe_smith 

So far I have tried doing this: Matching the line that contains "NAME" (couldn't get it working with the full one "NAME : ") with Find:

^.*\b(NAME)\b.*$ 

But I don't know how to replace the spaces after the match.

Is there a way to accomplish this with Regex?

0

2 Answers

Depending on your regex flavour, you can do:

  • Find: (?:^NAME : |\G(?!^))\w+\K\h
  • Replace: _

A demo and explanation can be found here on Regex101.

6

It depends on where you're using the regex:

The following uses sed:

sed ':redo s/^\(\s*NAME\s*:\s*\S\+\)\s\+\([^_[:space:]]\)/\1_\2/ ;t redo' files 

The trick here is the t redo, which does a conditional branch back to the label redo, to rerun the replacement until it fails.

Note that the pattern includes some glue to make spaces around the : optional, ignore trailing white space and reduce multiple spaces to a single _.

11

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy