Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything after space in string

Tags:

regex

r

gsub

I would like to remove everything after a space in a string.

For example:

"my string is sad"

should return

"my"

I've been trying to figure out how to do this using sub/gsub but have been unsuccessful so far.

like image 205
user1214864 Avatar asked Feb 16 '12 21:02

user1214864


People also ask

How do you remove everything from a string after a character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you remove a character after a space in a string in Java?

Java has inbuilt methods to remove the whitespaces from the string whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip method removes the leading and trailing spaces present in the string. Also, it is Uniset/Unicode character aware.

How do you cut all spaces in a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do I delete everything after a character in Notepad ++?

If you want to delete all the text after a character or string (to the right) in Notepad++ you would need to make use of regex. So, simply add . * to delete all characters after the string or character on each that you want to delete from a line.


2 Answers

You may use a regex like

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

See the regex demo.

Here, sub will only perform a single search and replace operation, the .* pattern will find the first space (since the regex engine is searching strings from left to right) and .* matches any zero or more characters (in TRE regex flavor, even including line break chars, beware when using perl=TRUE, then it is not the case) as many as possible, up to the string end.

Some variations:

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

See the online R demo.

like image 55
Wiktor Stribiżew Avatar answered Sep 17 '22 15:09

Wiktor Stribiżew


strsplit("my string is sad"," ")[[1]][1]
like image 44
baptiste Avatar answered Sep 17 '22 15:09

baptiste