Delete everything after a space in a line

I would like to delete everything after a space in the line.

For instance:

"my string is sad" 

must return

 "my" 

I tried to figure out how to do this with sub / gsub, but so far without success.

+7
source share
4 answers
 strsplit("my string is sad"," ")[[1]][1] 
+10
source

or, replace everything behind the first space with nothing:

 gsub(' [Az ]*', '' , 'my string is sad') 

And with the numbers:

 gsub('([0-9]+) .*', '\\1', c('c123123123 0320.1')) 
+9
source

You can use regular expressions like

 sub(" .*", "", x) 

See a demo of regular expressions .

Here, sub will only perform one search and replace operation, a pattern .* Find the first space (since the regex engine looks for strings from left to right), a .* Matches any zero or more characters (in the TRE regex variant, even including line break characters, be careful when using perl=TRUE , then this is not) as much as possible, up to the end of the line.

Some options:

 sub("[[:space:]].*", "", x) # \s or [[:space:]] will match more whitespace chars sub("(*UCP)(?s)\\s.*", "", x, perl=TRUE) # PCRE Unicode-aware regex stringr::str_replace(x, "(?s) .*", "") # (?s) will force . to match any chars 

Watch online R demo .

+7
source

If you want to do this with a regex:

 gsub('([Az]+) .*', '\\1', 'my string is sad') 
+4
source

Source: https://habr.com/ru/post/1396927/


All Articles