DevSenGoku
DevSenGoku

Reputation: 75

Regex to reject a statement having only words, but accept a statement having words and numbers

There is a text file like:

My Name Is Sam

My 0.22 1.65

Name 2.21 2.99

Is 3.31 4.12

Sam 4.97 5.95

I want to reject the first statement having only words.

I want to consider the statement having words and numbers so that I can put it in an array.

How can I do this in Regex?

My code works for English, but not for characters like Chinese.

while ((line2 = streamReader2.ReadLine()) != null)
{
    // If line contains numbers and words, then split if by space and store in an array.
    if (Regex.IsMatch(line2, @"[^0-9\p{L}_ ]+", RegexOptions.IgnoreCase)) 
    {
        wordArray = line2.Split(null); //split each string by blankspace
    }
}

Upvotes: 1

Views: 68

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627020

You may omit regex here and use if (line2.Any(Char.IsDigit) && line2.Any(Char.IsLetter)). This will only return true if the line contains both a Unicode letter and any Unicode digit.

Then, use the following fix:

var wordArray = new List<String[]>();               // Declare wordArray
while ((line2 = streamReader2.ReadLine()) != null)
{
    if (line2.Any(Char.IsDigit) && line2.Any(Char.IsLetter)) // If line2 contains letter and digit
        wordArray.Add(line2.Split());  // Add the line split with whitespace to wordArray
}

See the C# demo

Upvotes: 1

Related Questions