Matt
Matt

Reputation: 337

Select first space in line

I need regex to select the first space in line regardless of number of spaces or words on that line.

E.g.

aaa bbb ccc ddd fff ggg 

I want only first space to be selected between 'aaa' and 'bbb'.

I created something like ^(\S+)\s which selects 'aaa_' but I only want the space to be selected and only first one in the line even if there is more spaces in it.

Thanks for feedback

Upvotes: 1

Views: 5662

Answers (6)

Toto
Toto

Reputation: 91373

Just exchange your capture group, instead of:

^(\S+)\s

type in the Search what: box:

^\S+(\s)

The first space of a line will be captured in first group.

Upvotes: 0

Shannon
Shannon

Reputation: 46

If I understand correctly, you want to change the first single white space character to a tab. Find and replace all should be fairly straightforward in Notepad++, just be sure to select the regular expressions.

You are correct in the way you identify the character:

^(\S+)\s    

resulting in 'aaa_'

But when you go to replace it try this:

\1\t

resulting in 'aaa\t'

Upvotes: 1

Jonny 5
Jonny 5

Reputation: 12389

$str = "aaa bbb ccc ddd fff ggg";

For PHP preg_replace: If you want to replace the first white-space only, set limit:

echo preg_replace('/\s/', "_", $str, 1);

output:

aaa_bbb ccc ddd fff ggg

Upvotes: 1

Joey
Joey

Reputation: 354356

You can match the first space with a regex that just contains a space, e.g.:

PS Home:\> [regex]::Match('aaa bbb ccc ddd fff ggg', ' ')

Groups   : { }
Success  : True
Captures : { }
Index    : 3
Length   : 1
Value    :

Note that \s would match everything that is whitespace, including tabs, non-breaking space and a lot of other things, not just U+0020.

Upvotes: 1

kwelsan
kwelsan

Reputation: 1219

PHP example with regex

$str = 'aaa bbb ccc ddd fff ggg ';
preg_match_all('/\s/', $str, $matches);
print "-->".$matches[0][0]."<--";    

Upvotes: 1

Barmar
Barmar

Reputation: 780688

Use:

/\s/

If you don't use the global flag g, a regexp matches the first instance.

Upvotes: 3

Related Questions