简体   繁体   中英

How to Restrict a blank space at start and end of the string in C# code while loading .csv file

In our C# code while we are loading the xx.csv file with some Input values we are facing the issue with blank space at start and end of the string. While xx.csv file validation it is accepting the blank space at beginning and end of the string.While loading we are validating the input values of xxx.csv file with the function Regex.IsMatch(string input, string pattern ). Please find the example pattern at below.

string input = "STACK OVER FLOW IN";

string pattern = "^[A-Za-z0-9 .,']*[A-Za-z0-9 .,']+[A-Za-z0-9 _.,']*$";

Expected Result:

string input = "STACK OVER FLOW IN "; => Reject.

string input = " STACK OVER FLOW IN"; => Reject.

string input = "STACK OVER FLOW IN"; => Accept.

Can anyone please suggest me how can I prohibit the blank space at beginning and end of the string only ( Note: We need to accept the blank space between strings )?

Simply, something like:

bool CheckInput(string input)
{
    if (input.FirstOrDefault() == ' ' || input.FirstOrDefault() == ' ')
    return false;
    return true;
}

This will return `true` for an empty string.

\S matches anything except spaces, I suppose you can use something like:

^\S.+\S$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM