Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string before any first number

string test = " Puerto Rico 123 " ;

I would like to obtain only "Puerto Rico". The idea is that instead of 123 it can be any number. How can I achieve this?

like image 704
Florin M. Avatar asked Jan 18 '17 12:01

Florin M.


People also ask

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split a string before a number in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string after a number?

a = a. replaceAll("[0-9]+","$1 "); String[] b = a. split(" "); It can also be customized in case your string contains other spaces, by substituting a character guaranteed not to appear in your string instead of the space.

How do you split a string into values?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

I suggest using regular expressions which is quite easy in the context: get all the non-digit [^0-9]* characters from the beginning ^ of the string:

string test = " Puerto Rico 123 ";

string result = Regex.Match(test, @"^[^0-9]*").Value;

Linq is an alrernative:

string result = string.Concat(test.TakeWhile(c => c < '0' || c > '9'));

In case you want to trim the leading and trailing spaces (and have "Puerto Rico" as the answer, not " Puerto Rico "), just add .Trim(), e.g.:

string result = Regex.Match(test, @"^[^0-9]*").Value.Trim();
like image 123
Dmitry Bychenko Avatar answered Sep 22 '22 06:09

Dmitry Bychenko


You could do it with Regex as suggested, but you can try with this one as well:

var str = " Puerto Rico 123 ";
var firstDigit = str.FirstOrDefault(c => char.IsDigit(c));

if (firstDigit != default(char))
{
    var substring = str.Substring(0, str.IndexOf(firstDigit));
}

It returns the value of the first digit in your string if there is any, or '\0' if there is no digit in your string. After that, we check if first digit is anything other than '\0', if so, we take substring of the initial string from the beginning until the first occurrence of the digit in your string.

like image 31
msmolcic Avatar answered Sep 23 '22 06:09

msmolcic