Reputation: 701
Given a string that ends in a whitespace character return true.
I'm sure I should be able to do this with regular expressions but I'm not having any luck. MSDN reference for regular expressions tells me that \s
should match on a whitespace, but I can't figure the rest out.
Upvotes: 4
Views: 6114
Reputation: 415840
The Trim()
function (and TrimEnd()
) removes all whitespace, so you can do this by comparing a string to the trimmed version:
if (myString != myString.TrimEnd())
{
//the string ends with whitespace
}
As a practical matter, other answers already here of course are more direct and faster just accomplishing the test. However, my experience is most of the time when you need to know this you'll soon need to use the trimmed string, as well. In these circumstances, it's often useful to put that into a variable, to avoid needing to call TrimEnd()
more than once:
var trimmed = myString.TrimEnd();
if (myString != trimmed)
{
//use trimmed here
}
Upvotes: 2
Reputation: 9401
You certainly can use a regex for this, and I'm sure someone smarter than me will post exactly how to do it :), but you probably don't want to use a regex in this case. It will almost certainly be faster to simply ensure that the string is not null or empty, and then to return
Char.IsWhiteSpace(myString[length - 1])
Upvotes: 14
Reputation: 887469
Like this:
if (Regex.IsMatch(someString, @"\s+$"))
\s
matches whitespace+
means one or more of the preceding expression$
means the end of the stringUpvotes: 5