Reputation:
Can any one give me correct Regular Expression to accept Name starting with characters and ending with characters, in middle i can allow - Ex: ABC or ABC-DEF or ABC-DEF-GHI But it should not start or end with - Ex: -ABC or -ABC- or ABC-
Here is my Regular Expression:
var regex = /^[A-Za-z]-?[A-Za-z]*-?([A-Za-z]+)+$/
This works perfactly fine for me, but if suppose i want to give name as AB-CD-EF-GH than this don't work. Note: Remember that Name should start with Characters and End with Characters and in between i can have - but not -- twice. It has to be associated with characters like a-b-c-d
Upvotes: 1
Views: 3217
Reputation: 16033
I believe this is what you want :
/^[A-Z](-[A-Z]+)*[A-Z]$/i
Analysis :
/^ Start of string
[A-Z] Any alphabetic character
( Group
- A hyphen character
[A-Z]+ One or more alphabetic characters
)* 0 or more repititons of group
[A-Z] Any alphabetic character
$/i End of string, allow upper or lower case alpha
Upvotes: 1
Reputation: 1144
var rgx = /^[A-Za-z]+(-[A-Za-z]+)*$/;
rgx.test("ABC"); // true
rgx.test("ABC-DEF"); // true
rgx.test("AB-CD-EF-GH"); // true
rgx.test("-AB-CD-EF-GH"); // false
rgx.test("AB-CD-"); // false
rgx.test("AB--CD"); // false
Upvotes: 0
Reputation: 67968
^[A-Za-z]+(?:-[A-Za-z]+)*$
This simple regex will do it for you.See demo.
https://regex101.com/r/sJ9gM7/55
var re = /^[A-Za-z]+(?:-[A-Za-z]+)*$/gim;
var str = 'ABC\nABC-DEF\n-ABC\nABC-\nAB-CD-EF-GH\n';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Upvotes: 1
Reputation: 626794
You can use .*
inside to allow any number of any characters except for a newline:
var regex = /^(?!.*--.*$)[A-Za-z].*[A-Za-z]$/
(?!.*--.*$)
will make sure double hyphens are not allowed.
Please check the regex demo here.
function ValIt(str)
{
var re = /^(?!.*?--.*?$)[A-Za-z].*[A-Za-z]$/g;
if ((m = re.exec(str)) !== null)
return true;
else
return false;
}
document.getElementById("res").innerHTML = 'RTT--rrtr: ' + ValIt('RTT--rrtr') + "<br>ER#$-wrwr: "+ ValIt('ER#$-wrwr') + "<br>Rfff-ff-d: " + ValIt('Rfff-ff-d');
<div id=res />
Upvotes: 0