Hopefully a simple one!
I've been trying to get this to work for several hours now but am having no luck, as I'm fairly new to regexp I may be missing something very obvious here and was hoping someone could point me in the right direction. The pattern I want to match is as follows: -
At least 1 or more numbers + "##" + at least 1 or more numbers + "##" + at least 1 or more numbers
so a few examples of valid combinations would be: - 1##2##3 123#123#123 0##0##0
A few invalid combinations would be a##b##c 1## ##1
I've got the following regexp like so: -
[\d+]/#/#[\d+]/#/#[\d+]
And am using it like so (note the double slashes as its inside a string): -
var patt = new RegExp("[\\d+]/#/#[\\d+]/#/#[\\d+]");
if(newFieldValue!=patt){newFieldValue=="no match"}
I also tried these but still nothing: -
if(!patt.text(newFieldValue)){newFieldValue==""}
if(patt.text(newFieldValue)){}else{newFieldValue==""}
But nothing I try is matching, where am I going wrong here?
Any pointers gratefully received, cheers!
1) I can't see any reason to use the RegExp
constructor over a RegExp literal for your case. (The former is used primarily where the pattern needs to by dynamic, ie is contributed to by variables.)
2) You don't need a character class if there's only one type of character in it (so \\d+
not [\\d+]
3) You are not actually checking the pattern against the input. You don't apply RegEx by creating an instance of it and using ==
; you need to use test()
or match()
to see if a match is made (the former if you want to check only, not capture)
4) You have ==
where you mean to assign ( =
)
if (!/\d+##\d+##\d+/.test(newFieldValue)) newFieldValue = "no match";
You put +
inside the brackets, so you're matching a single character that's either a digit or +
, not a sequence of digits. I also don't understand why you have /
before each #
, your description doesn't mention anything about this character. Use:
var patt = /\d+##\d+##\d+/;
You should use the test method of the pat regex
if (!patt.test(newFieldValue)){ newFieldValue=="no match"; }
once you have a valid regular expression.
Try this regex :
^(?:\d+##){2}\d+$
Demo: http://regex101.com/r/mE8aG7
With the following regex
[\\d+]/#/#[\\d+]/#/#[\\d+]
You would only match things like:
+/#/#5/#/#+
+/#/#+/#/#+
0/#/#0/#/#0
because the regex engine sees it like on the schema below:
就像是:
((-\\s)?\\d+##)+\\d+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.