regular expression to match name with only one spaces - javascript

I have a string condition in js where i have to check whether name entered in text box contains with one space only.
pattern: name.status === 'full_name' ? /^[a-zA-Z.+-.']+\s+[a-zA-Z.+-. ']+$/ : /^[a-zA-Z.+-. ']+$/
But the above regex matches names ending with 2 spaces also.
I need to match it such that the entered name should accept only one space for a name string. So the name will have only one space in between or at the end.

Two observations: 1) \s+ in your pattern matches 1 or more whitespaces, and 2) [+-.] matches 4 chars: +, ,, - and ., it is thus best to put the hyphen at the end of the character class.
You may use
/^[a-zA-Z.+'-]+(?:\s[a-zA-Z.+'-]+)*\s?$/
See the regex demo
Details
^ - start of string
[a-zA-Z.+'-]+ - 1 or more letters, ., +, ' or -
(?:\s[a-zA-Z.+'-]+)* - zero or more sequences of:
\s - a single whitespace
[a-zA-Z.+'-]+ - 1 or more letters, ., +, ' or - chars
\s? - an optional whitespace
$ - end of string.
Note: if the "names" cannot contain . and +, just remove these symbols from your character classes.

/^\S+\s\S+$/
try this
Some explanations:
^ - start of string
\s - single whitespace
\S - everything except whitespace
"+"- quantifier "one or more"
$ - end of string

you could also use word boundaries...
function isFullName(s) {
return /^\b\w+\b \b\w+\b$/.test(s);
}
['Giuseppe', 'Mandato', 'Giuseppe Mandato']
.forEach(item => console.log(`isFullName ${item} ? ${isFullName(item)}`))

Related

Regex to not allow special character without prefix or suffix

I was writing regex for the following validate a string. I wrote the following regex.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}$
it validates for
No space in beginning.
no two consecutive space allowed.
The problem is it allows a single special character. it should not allow a special character unless it is suffixed or prefixed with alpha-numeric character.
Examples:
# -> not allowed.
#A or A# or A2 or 3A is allowed.
One option is to assert that the string does not contain a single "special" char or 2 special chars next to each other using a negative lookahead.
^(?!.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s])(?!.*(?:^| )[^a-zA-Z0-9\s](?!\S))\S+(?: \S+)*$
Explanation
^ Start of string
(?! Negative lookahead, assert that what is at the right does not contain
.*[^a-zA-Z0-9\s][^a-zA-Z0-9\s] match 2 chars other than a-zA-Z0-9 or a whitespace char next to each other
) Close lookahead
(?! Negative lookahead, assert that what is at the right does not contain
.*(?:^| )[^a-zA-Z0-9\s](?!\S) Match a single char other than a-zA-Z0-9 or a whitespace char
) Close lookahead
\S+(?: \S+)* Match 1+ non whitespace chars and optionally repeat a space and 1+ non whitespace chars
$ End of string
Regex demo
Please omit the '$' symbol from the regex because it represents the end of the sentence.
^[^\s]+[a-z]{0,}(?!.* {2})[ a-zA-z]{0,}
So when applying the above regex to the following, it finds only '# '.
#A A# A2 3A

Angularjs regex validation

I want to make an Angularjs regex validation that allow all alphabets, numbers, space and following special characters ! ' " & - ( )
You may use
ng-pattern="/^[a-zA-Z0-9\s!'\x22&()-]*$/"
Details
^ - start of string
[a-zA-Z0-9\s!'\x22&()-]* - 0 or more:
a-zA-Z - ASCII letters
0-9 - ASCII digits
\s - whitespaces
!'\x22&()- - !, ', " (\x22 matches "), &, (, ) or - (the hyphen must be at the end/start of the character class or escaped to denote a literal -)
$ - end of string.

Regex not working for comma separated list of strings

I need a regex for following values:
Ha2:123hD,Ha2:123hD,Ha2:123hD - correct match - true
Ha2:123hD,Ha2:123hD,Ha2:123hD, - comma on end - false
Ha2:123hD,Ha2:123hD,Ha2:123hD,,Ha2:123hD - double comma- false
,Ha2:123hD,Ha2:123hD,Ha2:123hD - comma at start- false
I am trying the following regex:
/(([a-zA-Z0-9]+)(\W)([a-zA-Z0-9]+))/
/(([a-zA-Z0-9]+)(\W)([a-zA-Z0-9]+,)*([a-zA-Z0-9]+)(\W)([a-zA-Z0-9])+$)/
But it is not working.
You could put the comma at the start of the repeating group.
/^[a-zA-Z0-9]+[:][a-zA-Z0-9]+(?:,[a-zA-Z0-9]+[:][a-zA-Z0-9]+)*$/
If you only need to check for these fix strings (As I have to guess from your question), this will work ^(Ha2:123hD,)*Ha2:123hD$
And otherwise, you just can follow this expression and replace the Ha2:123hD with your wildcard expression.
Also check this website:
https://regex101.com/
It explains nicely how the single symbols of a regex work.
To only match comma-seaprated alphanumeric + : string lists you may use
/^[a-zA-Z0-9:]+(?:,[a-zA-Z0-9:]+)*$/
See the regex demo
Explanation:
^ - start of string anchor
[a-zA-Z0-9]+ - a character class matching 1 or more (due to + quantifier)
ASCII letters or digits or :
(?: - start of a non-capturing group....
, - a comma
[a-zA-Z0-9:]+ - a character class matching 1 or more (due to + quantifier) ASCII letters or digits or :
)* - .... 0 or more occurrences (due to the * quantifier)
$ - end of string.

remove unwanted groups of characters from string using regex

Given: 1999 some text here 1.3i [more]
Needed: some text here
The following regex - replace(/[\d{4} |\d\.*$]/,'') - failed, it just removed the first digit. Any idea why and how to fix it?
var s = "1999 some text here 1.3i [more]"
console.log(s.replace(/[\d{4} |\d\.*$]/,''))
The regex you have removes the first digit only because it matches just 1 char - either a digit, {, 4, }, space, |, ., * or $ (as [...] formed a character class), just once (there is no global modifier).
You may use
/^\d{4}\s+|\s*\d\..*$/g
See the regex demo
Basically, remove the [ and ] that form a character class, add g modifier to perform multiple replacements, and add .* (any char matching pattern) at the end.
Details:
First alternative:
- ^ - start of string
- \d{4} - 4 digits
- \s+ - 1+ whitespaces
Second alternative:
- \s* - 0+ whitespaces
- \d - a digit
- \. - a dot
- .* - any 0+ chars up to...
- $ - the end of the string
var rx = /^\d{4}\s+|\s*\d\..*$/g;
var str = "1999 some text here 1.3i [more]";
console.log(str.replace(rx, ''));

how to understand this regex pattern

Javascript regex pattern I find in less:
/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/
especially this section:
\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9])
([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(
Let's work it from the inside out, using MDN as reference when necessary:
(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9])
(?:) is a non-capturing parenthesis. It groups and matches, but doesn't save the results. Inside that group is 1-6 hex digits followed by an optional space or any character other than a hex character.
(?:[\w-]|\\ above)+
Again, a non-capturing parenthesis, this time of \w, which is any alphanumeric character + _, and since there's [\w-], that's "any alphanum + -_". Then there's an or, a \ character, and the above. Together, that makes this parenthesis group read as: "Any single alphanumeric character, underscore or hyphen, or a backslash followed by either anything not a hexdigit or a hexstring of 1 to 6 characters." The + means "at least 1 instance of the group."
^([#.]above)\s*(
Now we have ^[#.] which means "the line must start with # or . followed by the above, with any number of spaces, followed by a left parenthesis.
TL;DR:
When you add that all up, you get:
"A line that starts with either # or . followed by one or more of:
alphanumeric characters, _ or - OR
a backslash followed by a one to six digit hexstring followed by a single optional space OR
a backslash followed by a single nonhexdigit character
followed by any number of whitespace and then a (".
If a match is found, the entire part before the whitespace and ( is stored in the result of the search.

Categories

Resources