简体   繁体   中英

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.

Eg

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

Use:

/\s/

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

PHP example with regex

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

You can match the first space with a regex that just contains a space, eg:

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.

$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

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM