We help IT Professionals succeed at work.

c# regex to find string containing just one character

lambch0p
lambch0p asked
on
Hi,

I need a regular expression to check if a string is made up of just one character.  This is basically to check for lines in a CSV file that have no data in the fields and therefore just contains commas.

This will be incorporated into a generic script, so the actual delimeter, and the number of fields will be abitrary, so I can't just count the number of seperators.  There's probably a simpler way of doing this that i'm over looking.

Thanks

M
Comment
Watch Question

Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
Generally you wouldn't use a regular expression for such a check when a length check will do instead, but matching pattern:
^.$
will only match on character if that's really what you want.
Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
Typo: "on character" should be "one character"

Commented:
Have a look at this: http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_25043490.html
Look at the solution I had posted there (need to scroll a bit down) and use it for creating a way to handle delimeters.
Also, you don't need a regular expression to check if a string has just one character:
 
You can use myString.length == 1
IT Guru
Most Valuable Expert 2011
Commented:
Hmmm... think I misinterpreted the question... I believe you mean it could be any number of occurrences of one character like ",,,," or "||||".

Try this pattern instead:
^(.)\1*$

Author

Commented:
Thanks Guys.

Terry's solution was exactly what I was after.