Regular expression
[A-Za-z_-]+
should match strings that only have upper and lower case letters, underscores, and a dash
but when I run in chrome console
/[A-Za-z_-]+/.test("johmSmith12")
Why it returns true
Because you didn't anchor the expression. You need to add ^ and $, which match beginning and end of string.
For example:
^[A-Za-z_-]+$
Just the [A-Za-z_-]+ will match johnSmith in your example, leaving out the 12 (as David Starkey pointed out).
It is due to your regex looking for any sequence of characters within the test string that matches the regex. In your example, "johnSmith" matches your regex criteria, and so test returns true.
If you instead put ^ (start of string) and $ (end of string) at the ends of your regex, then you would assert that the entire string must match your regex:
/^[A-Za-z_-]+$/.test("johnSmith12");
This will return false.
Related
What is the difference between "\\w+#\\w+[.]\\w+" and "^\\w+#\\w+[.]\\w+$"? I have tried to google for it but no luck.
^ means "Match the start of the string" (more exactly, the position before the first character in the string, so it does not match an actual character).
$ means "Match the end of the string" (the position after the last character in the string).
Both are called anchors and ensure that the entire string is matched instead of just a substring.
So in your example, the first regex will report a match on email#address.com.uk, but the matched text will be email#address.com, probably not what you expected. The second regex will simply fail.
Be careful, as some regex implementations implicitly anchor the regex at the start/end of the string (for example Java's .matches(), if you're using that).
If the multiline option is set (using the (?m) flag, for example, or by doing Pattern.compile("^\\w+#\\w+[.]\\w+$", Pattern.MULTILINE)), then ^ and $ also match at the start and end of a line.
Try the Javadoc:
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
^ and $ match the beginnings/endings of a line (without consuming them)
I'm using this regexp:
/[^+][a-z]/.test(str)
I'm trying to ensure that if there are any letters ([a-z]) in a string (str) not proceeded by a plus ([^+]) , a match is found and therefore it will return true.
It mostly works except when there is only one character in the string. For example, a returns false, even though there is no plus sign preceding it.
How can I ensure it works for all strings including one character strings. Thanks!
Add a ^ as an alternative to [^+]:
/(?:^|[^+])[a-z]/.test(str)
^^^^^^^^^^
The (?:^|[^+]) is a non-capturing alternation group matching either the start of the string (with ^) or (|) any char other than + (with [^+]).
What does this "/^\s*$/" mean as I tried to learn it from here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions but can't get it meaning?
fn: function (val) {
return typeof val === 'string' ?
!/^\s*$/.test(val) : val !== undefined && val !== null;
}
This
/^\s*$/
is a RegExp object
The code snippet
/^\s*$/.test(val)
uses RegExp test method to test whether a string val is empty or only contains spaces. From the docs:
The test() method executes a search for a match between a regular
expression and a specified string. Returns true or false.
If you take a look at this regex in this tutorial, it will show you the following explanation:
^ asserts position at start of the string
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
Basically, it means that:
/^...$/
matches a string from the beginning to the end, and
\s*
matches zero or more occurrences of white space characters
Here ^ means the beginning of expression.
\s* means 0 or more occurrences of space characters(' ', tab etc)
$ means end of the string.
so /^\s*$/ is the regex for empty string or string with only spaces.
/^\s*$/
first /{regex is here}/ is how u write regex here
^{somethingelse}$ is meaning started and ended in the middle regex
\s is any string character
'*' means zero or more
so it means all the element is character, not a number or symbol or spaces
Good Day,
I'm creating a javascript function to exclude certain codes from the database.
For example, the following are valid codes:
FF99
1G499
RNDD
In other words, I want the codes to consist of only alphanumerics. I opened up the console in Chrome and tried:
> re = new RegExp('\w+')
> re.test('whatever')
true
> re.test('what???')
true
> var test = new RegExp('^\w+')
> test.test('what')
true
> test.test('what999')
true
> test.test('what???')
true
So I know that \w can either be a 0-9, a-z, A-Z. I don't know why the regex is passing if I enter '?' when they shouldn't.
Am I missing something?
You're misinterpreting your results. The regexp \w+ means "one or more word characters". It doesn't specify where in the string these characters can be found. In all of your tests, the provided string contains at least one word character, so they all pass.
What you're meaning to do is ensure the string contains only alphanumerics. Try the following regex:
^\w+$
Broken down, this means:
^ = match start of string
\w = letters or digits
+ = one or more of the previous element (in this case, the set) (this is greedy)
$ = match the end of the string
In English, this means, "between the start and end of the string, only alphanumeric characters will match. Match as many as possible, or none at all"
Documentation on ^ and $
Note: if you write your regex as a string, you need to escape the \ like so:
new RegExp("^\\w+$")
Otherwise, JavaScript will interpret \w as an escape sequence, which it is not. You can also use the syntax
new RegExp(/^\w+$/)
in which case you don't need to escape the \, since it isn't a string.
Test is returning true because the pattern \w+ is matching the alphanumeric part in your test strings.
re.test('what???') for example will return true because it matches what.
If you only want to match strings consisting of only alphanumeric characters, you should use something like ^\w+$ .
I am having a bit of trouble with one part of a regular expression that will be used in JavaScript. I need a way to match any character other than the + character, an empty string should also match.
[^+] is almost what I want except it does not match an empty string. I have tried [^+]* thinking: "any character other than +, zero or more times", but this matches everything including +.
Add a {0,1} to it so that it will only match zero or one times, no more no less:
[^+]{0,1}
Or, as FailedDev pointed out, ? works too:
[^+]?
As expected, testing with Chrome's JavaScript console shows no match for "+" but does match other characters:
x = "+"
y = "A"
x.match(/[^+]{0,1}/)
[""]
y.match(/[^+]{0,1}/)
["A"]
x.match(/[^+]?/)
[""]
y.match(/[^+]?/)
["A"]
[^+] means "match any single character that is not a +"
[^+]* means "match any number of characters that are not a +" - which almost seems like what I think you want, except that it will match zero characters if the first character (or even all of the characters) are +.
use anchors to make sure that the expression validates the ENTIRE STRING:
^[^+]*$
means:
^ # assert at the beginning of the string
[^+]* # any character that is not '+', zero or more times
$ # assert at the end of the string
If you're just testing the string to see if it doesn't contain a +, then you should use:
^[^+]*$
This will match only if the ENTIRE string has no +.