Regular Expression for alphabets with spaces - javascript

I need help with regular expression. I need a expression which allows only alphabets with space for ex. college name.
I am using :
var regex = /^[a-zA-Z][a-zA-Z\\s]+$/;
but it's not working.

Just add the space to the [ ] :
var regex = /^[a-zA-Z ]*$/;

This is the better solution as it forces the input to start with an alphabetic character. The accepted answer is buggy as it does not force the input to start with an alphabetic character.
[a-zA-Z][a-zA-Z ]+

This will allow space between the characters and not allow numbers or special characters. It will also not allow the space at the start and end.
[a-zA-Z][a-zA-Z ]+[a-zA-Z]$

This will accept input with alphabets with spaces in between them but not only spaces. Also it works for taking single character inputs.
[a-zA-Z]+([\s][a-zA-Z]+)*

Special Characters & digits Are Not Allowed.
Spaces are only allowed between two words.
Only one space is allowed between two words.
Spaces at the start or at the end are consider to be invalid.
Single word name is also valid : ^[a-zA-z]+([\s][a-zA-Z]+)*$
Single word name is in-valid : ^[a-zA-z]+([\s][a-zA-Z]+)+$

Regular expression starting with lower case or upper case alphabets but not with space and can have space in between the alphabets is following.
/^[a-zA-Z][a-zA-Z ]*$/

This worked for me
/[^a-zA-Z, ]/

This will work too,
it will accept only the letters and space without any symbols and numbers.
^[a-zA-z\s]+$
^ asserts position at start of the string Match a single character
present in the list below [a-zA-z\s]
matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy) a-z matches a single
character in the range between a (index 97) and z (index 122) (case
sensitive) A-z matches a single character in the range between A
(index 65) and z (index 122) (case sensitive) \s matches any
whitespace character (equivalent to [\r\n\t\f\v ]) $ asserts position
at the end of the string, or before the line terminator right at the
end of the string (if any)

This worked for me, simply type in javascript regex validation
/[A-Za-z ]/

This one "^[a-zA-Z ]*$" is wrong because it allows space as a first character and also allows only space as a name.
This will work perfectly. It will not allow space as a first character.
pattern = "^[A-Za-z]+[A-Za-z ]*$"

This works for me
function validate(text) {
let reg = /^[A-Za-z ]+$/; // valid alphabet with space
return reg.test(text);
}
console.log(validate('abcdef')); //true
console.log(validate('abcdef xyz')); //true
console.log(validate('abc def xyz')); //true
console.log(validate('abcdef123')); //false
console.log(validate('abcdef!.')); //false
console.log(validate('abcdef#12 3')); //false

This will restrict space as first character
FilteringTextInputFormatter.allow(RegExp('^[a-zA-Z][a-zA-Z ]*')),

This will work for not allowing spaces at beginning and accepts characters, numbers, and special characters
/(^\w+)\s?/

Related

Regular expression to validate a string starts with a char and contains allowed chars

I need help with my regular expression written in javascript.
I have tried using the regularExpression generator online, and the best i can come up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
String first char MUST start with a-z (no alpha)
String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
String can be of max length 50 chars
Examples of success strings
username1
username.lastname
username-anotherstring1
this.is.also.ok
No good strings
1badusername
.verbad
-bad
also very bad has spaces
// Thanks
Almost (assuming "no alpha" means no uppercase letters)
https://regex101.com/r/O9hvLP/3
^[a-z]{1}[a-z0-9\.-]{0,49}$
The {1} is optional, I put it there for descriptive reasons
I think this should cover what you want
^[a-z][a-z0-9.-]{0,49}$
That is starts a-z but then has 0-49 of a-z, 0-9 or .-
Live example: https://regexr.com/5k8eu
Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z as well!
If the . and - can not be at the end, and there can not be consecutive ones, another option could be:
^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$
Explanation
^ Start of string
[a-z] Match a single char a-z
(?=[a-z0-9.-]{0,49}$) Assert 0-49 chars to the right to the end of string
[a-z0-9]* Match optional chars a-z0-9
(?:[.-][a-z0-9]+)* Optionally match either . or - and 1+ times a char a-z0-9
$ End of string
Regex demo

RegEx for single asterisk (*) and alphanumeric

I need a javascript regex that accepts any alphanumeric character (can be any amount of characters or 0 characters if an asterisk is present) and a single asterisk anywhere in the string (but it does not need the asterisk).
Matches
*
abc
*abc
abc*
a*bc
Invalid Matches
**
*_abc
*abc*
abc**
**abc
I have
^([A-Za-z\d*]?)+$
but that matches multiple asterisks and I'm not sure how to only allow one https://regex101.com/r/a1C9bf/1
You may use this regex with a negative lookahead:
/^(?!(?:.*\*){2})[A-Za-z\d*]+$/gm
Updated RegEx Demo
Negative lookahead (?!(?:.*\*){2}) fails the match if there are more than one * in input.
Without requiring any look-ahead, you could use ^([\da-zA-Z]+|[\da-zA-Z]*\*[\da-zA-Z]*)$
https://regex101.com/r/xW2IvR/2
You could do:
^(?=.)[A-Za-z\d]*\*?[A-Za-z\d]*$
This will match any string that that's at least one character long ((?=.)), starts with zero or more alphanumeric characters, contains an optional *, and ends with zero or more alphanumeric characters.
You could also replace [A-Za-z\d] with [^\W_] to make it a little shorter (but slightly harder to read):
^(?=.)[^\W_]*\*?[^\W_]*$
You want one match one of two possible cases:
an asterisk surrounded by zero or more alphanumeric characters
one or more alphanumeric characters
Then this is your regex:
^([a-zA-Z\d]*\*[a-zA-Z\d]*|[a-zA-Z\d]+)$

Character matching

I need to match a string to have words and not numbers, I need to match special characters such as $!:{}_ if they are part of the word but ignore otherwise.
I have a regex that matches for word and ignores numbers but cannot work out how to match special characters if they are part of the word but ignore otherwise.
Here is what I have correctly - /^d\s+/
Any help would be appreciated.
Allow words and letters only, and ignore any numbers. Special
characters such as (-_‘[]{}“£$&%!:;/) should either be ignored or
treated as part of the word they sit within.
Try using String.prototype.replace() with RegExp /\s\d+.*\d|\s+[^a-z]/ig to replace space character followed by digit followed by any character followed by digit , or space character followed by any character not a-z case insensitive
var str = "This is a test of 1,2,3 word-count - test.";
str = str.replace(/\s\d+.*\d|\s+[^a-z]/ig, "");
document.body.textContent = str;

How to extract the last word in a string with a JavaScript regex?

I need is the last match. In the case below the word test without the $ signs or any other special character:
Test String:
$this$ $is$ $a$ $test$
Regex:
\b(\w+)\b
The $ represents the end of the string, so...
\b(\w+)$
However, your test string seems to have dollar sign delimiters, so if those are always there, then you can use that instead of \b.
\$(\w+)\$$
var s = "$this$ $is$ $a$ $test$";
document.body.textContent = /\$(\w+)\$$/.exec(s)[1];
If there could be trailing spaces, then add \s* before the end.
\$(\w+)\$\s*$
And finally, if there could be other non-word stuff at the end, then use \W* instead.
\b(\w+)\W*$
In some cases a word may be proceeded by non-word characters, for example, take the following sentence:
Marvelous Marvin Hagler was a very talented boxer!
If we want to match the word boxer all previous answers will not suffice due the fact we have an exclamation mark character proceeding the word. In order for us to ensure a successful capture the following expression will suffice and in addition take into account extraneous whitespace, newlines and any non-word character.
[a-zA-Z]+?(?=\s*?[^\w]*?$)
https://regex101.com/r/D3bRHW/1
We are informing upon the following:
We are looking for letters only, either uppercase or lowercase.
We will expand only as necessary.
We leverage a positive lookahead.
We exclude any word boundary.
We expand that exclusion,
We assert end of line.
The benefit here are that we do not need to assert any flags or word boundaries, it will take into account non-word characters and we do not need to reach for negate.
var input = "$this$ $is$ $a$ $test$";
If you use var result = input.match("\b(\w+)\b") an array of all the matches will be returned next you can get it by using pop() on the result or by doing: result[result.length]
Your regex will find a word, and since regexes operate left to right it will find the first word.
A \w+ matches as many consecutive alphanumeric character as it can, but it must match at least 1.
A \b matches an alphanumeric character next to a non-alphanumeric character. In your case this matches the '$' characters.
What you need is to anchor your regex to the end of the input which is denoted in a regex by the $ character.
To support an input that may have more than just a '$' character at the end of the line, spaces or a period for instance, you can use \W+ which matches as many non-alphanumeric characters as it can:
\$(\w+)\W+$
Avoid regex - use .split and .pop the result. Use .replace to remove the special characters:
var match = str.split(' ').pop().replace(/[^\w\s]/gi, '');
DEMO

regular expression to avoid only special chars

I'm validating a input text box. I'm new to regexp. I want an expression which throws a validation error if all the characters of input are special characters. but it should allow special characters in the string.
-(**&^&)_) ----> invalid.
abcd-as jasd12 ----> valid.
currently validating for numbers and alphabets with /^[a-zA-Z0-9-]+[a-z A-Z 0-9 -]*$/
/[A-Za-z0-9]/ will match positive if the string contains at least 1 letter or number, which should be the same as what you're asking. If there are NO letters or numbers, that regex will evaluate as false.
According to your comment, special characters are !##$%^&*()_-, so you could use:
var regex = /^[!##$%^&*()_-]+$/;
if (regex.test(string))
// all char are special
If you have more special char, add them in the character class.
Use negative Lookahead:
if (/^(?![\s\S]*[^\w -]+)[\s\S]*?$/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
DEMO
EXPLANATION:
^(?!.[^\w -]+).?$
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*[^\w -]+)»
Match any single character «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match a single character NOT present in the list below «[^\w -]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A word character (letters, digits, and underscores) «\w»
The character “ ” « »
The character “-” «-»
Match any single character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
~[^a-zA-z0-9 ]+~ it will matches if the String doesnot contains atleast one alphabets and numbers and spaces in it.
Demo

Categories

Resources