Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first word from the string

Tags:

c#

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?

like image 967
Fast Chip Avatar asked Apr 17 '18 02:04

Fast Chip


People also ask

How do I get the first word of a string in SQL?

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.

How do I extract words from a string?

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.

How do I get the first word of a string in PHP?

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);

How do I extract the first two words in Excel?

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.


1 Answers

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.

like image 200
Jake Miller Avatar answered Nov 15 '22 21:11

Jake Miller