Home > Net >  Regex - has delimiter get a substring, no delimiter get the whole string
Regex - has delimiter get a substring, no delimiter get the whole string

Time:03-29

This is for Google Sheets so I am using REGEXEXTRACT that uses the RE2 flavor of regex.

I have two cases.

Case one, two strings with a delimiter. "String One, String Two". In this case I want to extract what's before the delimiter.

Case two, just one string. "String One". In this case, I want to extract the whole string.

I know it's possible to test the existence of the delimiter using a google sheets formula but I wonder if there is a possibility to do that just with a regex.

Thanks!

CodePudding user response:

With Regex

You can use the regex expression ^[^,]* to match a consecutive string of any characters except commas, starting at the beginning.

=regexextract(A1,"^[^,]*")

Split and Index

As others have noted, you can use the =split() formula to separate the input string by some delimiter. From there, you can use something like index() or array_constrain() to get the first element.

=index(split(A1,","),1,1)

CodePudding user response:

Thanks for all the help.

Following the previous answers, I came out with the formula =IFERROR(INDEX(SPLIT(A1,","),1),"")

Sometimes, regex is not the best solution ;-)

  • Related