Regular Expression for Alphabetical text with some exceptions

I am looking to for Regular Expression for a text field which accepts alphabets, also dots(.), brackets, -, & like

A.B.C
ABC (new),
A & A co.
A-abc.

I have my regular expression:

/^[A-z.&() ]+$/

code:

var regex = /^[a-z][a-z.()&-]+$/;
var sel = document.getElementById("TextBoxID").value;
if (sel != "-- Select --") {
if (!regex.test(sel.toString())) {
alert("Please use a proper name.");
}
} return false;

I want the string to mandatory start with alphabet. But seems like this is not working when I add - into the same, may be the syntax is wrong.

Answers


First, note that [A-z] is not the same as [A-Za-z], which is probably what you meant. If you look at an ASCII table, you can see that the range from A to z includes several special characters that you may not intend to include.

Second, since the dash - denotes a range in a character class (as above), it must be included last (or first, but more commonly last) in order to be interpreted as a literal dash.

So, what you really want is this:

/^[A-Za-z.()&-]+$/

And to assert that it starts with an alphabet:

/^[A-Za-z][A-Za-z.()&-]*$/
  ^^^^^^^^             ^

(Notice I've changed the + quantifer to a * quantifier.)

Finally, as @ExplosionPills had done, you can simplify the expression by making it case-insensitive:

/^[a-z][a-z.()&-]*$/i

Need Your Help

unable to launch facebook login page in Selenium

java facebook selenium selenium-webdriver wait

I am testing a web app, that has facebook login icon. The HTML is like:

Which ASP.NET Control should I use?

c# asp.net user-interface listbox repeater

I am unsure which asp.net control to use. I've tried / thought about with no avail.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.