user3723061
user3723061

Reputation: 41

Regex to replace only first space with dash

I want to replace only the FIRST space in the line with a dash. This is somewhat complicated because the parser automatically applies /g to apply to the whole line.

Sample input: A1 B2 Word word word

Desired Output: A1-B2 Word word word

I can't do a simple /\s/-/ because the automatic /g will change all the spaces to dashes. I have tried a negative lookback /s(?<\s\w) and several other variations (word and boundary matching) but I end up matching either all of the spaces or I match the first or last character with the space so that I end up clipping out too much.

How do I replace only the first space with a globally-applied pattern?

Upvotes: 0

Views: 748

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

You can use ^ to indicate the beginning of a line:

/^.*?\s/$1-/

Upvotes: 0

Ryan J
Ryan J

Reputation: 8323

You could try something like this:

/^(\S*)\s/$1-/

The ^ specifies the beginning of the line, the \S matching all non whitespace characters. This will assume you don't have any leading whitespace, else your first character will be replaced with a -.

Upvotes: 1

Related Questions