Search code examples
regex

extract the first word from a string - regex


I have the following string:


str1 = "cat-one,cat2,cat-3";
OR
str1 = "catone,cat-2,cat3";
OR
str1 = "catone";
OR
str1 = "cat-one";

The point here is words may/may not have "-"s in it

Using regex: How could I extract the 1st word?

Appreciate any help on this.

Thanks, L


Solution

  • It's pretty easy, just include allowed characters in brackets:

    ^([\w\-]+)