I would like to get only the first word of the string regardless of any character or punctuation in front of it.
Sometimes, there could be ,
or .
or !
. I don't want these characters.
var s = "Hello, World";
var firstWord = s.Substring(0, s.IndexOf(" "));
This gives me Hello,
. I would like to get Hello
only.
How do I achieve this?
If you want to get the first word in a string, you'll need some form of substring operation. You can do this wtih substr + instr to find the location of the first space.
We can use search() method from re module to find the first occurrence of the word and then we can obtain the word using slicing. re.search() method will take the word to be extracted in regular expression form and the string as input and and returns a re.
Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string. This function is case-sensitive. . strstr ( $sentence , ' ' , true);
In the Formulas Helper dialog, please do as follows: Select Text from the Formula type drop-down list; Select Extract the nth word in cell in the Choose a formula list box; In the Cell textbox, specify the cells that you will extract words from, and enter the number you want to extract word based on in The Nth textbox.
Simply use the following regex:
var s = "Hello, World";
var result = Regex.Match(s, @"^([\w\-]+)");
Console.WriteLine(result.Value); // Result is "Hello"
This will get the first word regardless of whether or not it ends with punctuation or simply precedes a space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With