Reputation: 81
I've been trying all combinations that I could find on google, but nothing seems to allow me the regex for all letters and only one special charachter..
Example of what Im trying to achieve:
Something-something (accepted)
something something (accepted)
-Something(not accepted)
SomethingSomething-(not accepted)
something-something-somthing(accepted)
So as you see, I need to be able to use all letters and special char - anywhere inbetween letters. Hopefully someone knows the answer on how to achieve this.
My code:
private void textBox8_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox8.Text) || !Regex.IsMatch(textBox8.Text, @"^[A-Za-z]\-+$"))
{
textBox8.BackColor = Color.Red;
}
else
{
textBox8.BackColor = Color.White;
}
}
Upvotes: 1
Views: 117
Reputation: 11032
You can use this regex
^[A-Za-z]+(?:[- ][A-Za-z]+)*$
Check here
Regex Breakdown
^ #Start of string
[A-Za-z]+ #Match alphabets
(?:[- ][A-Za-z]+)* #Match - followed by alphabets 0 or more times
$ #End of string
Upvotes: 1
Reputation: 34421
Try this. You didn't specify if the dash was required or not required. I assume the dash was optional.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"Something-something",
"-Something",
"SomethingSomething-",
"something-something-somthing",
"1234"
};
string pattern = @"^([A-Za-z]+[-\s]?[A-Za-z]+)+$";
foreach (string input in inputs)
{
Console.WriteLine("Input : '{0}', Match : '{1}'", input, Regex.IsMatch(input, pattern) ? "Yes" : "No");
}
Console.ReadLine();
}
}
}
Upvotes: 0
Reputation: 415
If you need letters before and after the hyphen:
[A-Za-z]+\-[A-Za-z]+
If you just need a hyphen and letters somewhere in the string
[A-Za-z]?\-[A-Za-z]?
Upvotes: 1
Reputation: 13652
Does this pattern work for you?
^([A-Za-z]+-)+[A-Za-z]+$
Matches
Something-Something
Something-Something-Something
S-o-m-e-t-h-i-n-g
Does not match
-Something
Something-
Something-Something-
Something
Upvotes: 0