Javascript - Matching a hyphen in regex - javascript

I'm trying to match a string using regex (of which I am new to) but I can't get it to match.
These should be accepted:
GT-00-TRE
KK-10-HUH
JU-05-OPR
These should not:
HTH-00-AS
HM-99-ASD
NM-05-AK
So the pattern goes 2 letters, hyphen, 2 digits (between 00 and 11 inclusive), hyphen, 3 letters.
So far the best I can come up with is:
var thePattern = /^[a-z]{2}[-][00-11][-][a-z]{3}$/gi;
I can't help but feel that I'm pretty close.
Can anyone give me any pointers?
Thanks.

This should be what you need:
var thePattern = /^[a-z]{2}[-](0\d|1[0-1])[-][a-z]{3}$/gi;
In order to do a range 00-11, you have to say "(0 followed by 0-9) or (1 followed by 0 or 1)". This is because specifying a range within [] only works for single digits. Luckily your case is pretty simple, otherwise it could get quite complex to work around that.

Your regex is OK, but for one thing: the digits matching is a bit more complex
(0\d|10|11)
you want to match a zero followed by a digit (\d) OR (|) a ten OR a eleven.
Something in square brackets represents just a single character in a range. [0-5] means any single digit between 0 and 5, [a-q] means any lowercase letter from a to q. There's no such thing as [00-11] because it would require to work on more than one character at a time.

Related

Javascript regex to make sure that string matches format x:y

I am trying to parse a string which has two numbers, both can be between 1 and 3 digits, and will have a colon in between. Here are some examples:
"1:1"
"1:12"
"12:1"
"123:12"
Also, the given string may also be invalid, and I need to detect if it is. My attempts so far to make sure the string is valid have looked like this: .match(/[1-9]\:[1-9]/);. But then I noticed that this wont work if a string such as this is inputted: "characters12:4characters". How would I go about validating the string to make sure it is in the format x:y?
Any help would be deeply appreciated.
Edit: numbers which contain 0 at the beginning is valid, but may not be given.
You may use
/^\d{1,3}:\d{1,3}$/
See the regex demo
Details
^ - start of a string
\d{1,3} - one, two or three digits (\d is a shorthand character class that matches any digit (it can also be written as a [0-9] character class) and {1,3} is a limited quantifier that matches1 to 3 consecutive occurrences of the quantified subpattern)
: - a colon
\d{1,3} - one, two or three digits
$ - end of the string.

Regex exact match on number, not digit

I have a scenario where I need to find and replace a number in a large string using javascript. Let's say I have the number 2 and I want to replace it with 3 - it sounds pretty straight forward until I get occurrences like 22, 32, etc.
The string may look like this:
"note[2] 2 2_ someothertext_2 note[32] 2finally_2222 but how about mymomsays2."
I want turn turn it into this:
"note[3] 3 3_ someothertext_3 note[32] 3finally_2222 but how about mymomsays3."
Obviously this means .replace('2','3') is out of the picture so I went to regex. I find it easy to get an exact match when I am dealing with string start to end ie: /^2$/g. But that is not what I have. I tried grouping, digit only, wildcards, etc and I can't get this to match correctly.
Any help on how to exactly match a number (where 0 <= number <= 500 is possible, but no constraints needed in regex for range) would be greatly appreciated.
The task is to find (and replace) "single" digit 2, not embedded in
a number composed of multiple digits.
In regex terms, this can be expressed as:
Match digit 2.
Previous char (if any) can not be a digit.
Next char (if any) can not be a digit.
The regex for the first condition is straightforward - just 2.
In other flavours of regex, e.g. PCRE, to forbid the previous
char you could use negative lookbehind, but unfortunately Javascript
regex does not support it.
So, to circumvent this, we must:
Put a capturing group matching either start of text or something
other than a digit: (^|\D).
Then put regex matching just 2: 2.
The last condition, fortunately, can be expressed as negative lookahead,
because even Javascript regex support it: (?!\d).
So the whole regex is:
(^|\D)2(?!\d)
Having found such a match, you have to replace it with the content
of the first capturing group and 3 (the replacement digit).
You can use negative look-ahead:
(\D|^)2(?!\d)
Replace with: ${1}3
If look behind is supported:
(?<!\d)2(?!\d)
Replace with: 3
See regex in use here
(\D|\b)2(?!\d)
(\D|\b) Capture either a non-digit character or a position that matches a word boundary
(?!\d) Negative lookahead ensuring what follows is not a digit
Alternations:
(^|\D)2(?!\d) # Thanks to #Wiktor in the comments below
(?<!\d)2(?!\d) # At the time of writing works in Chrome 62+
const regex = /(\D|\b)2(?!\d)/g
const str = `note[2] 2 2_ someothertext_2 note[32] 2finally_2222 but how about mymomsays2.`
const subst = "$13"
console.log(str.replace(regex, subst))

Javascript regex: check if a string is alphanumeric AND it contains a letter (at least)

The string length can be 4 - 12 characters.
It may contain ONLY letters and numbers, but it has to contain at least 1 number.
And I need to solve this with a single regex pattern.
I tried something like:
/^(?=.*[a-z]*)(?=.*[0-9]+).{4,12}$/i
This won't accept less than 4 or more than 12 chars and it also checks if the string contains a number, but obviously it's not good because of the .* parts.
I wasn't able to figure out how to exclude all non-alphanumeric characters.
Any help would be appreciated!
Thanks in advance!
I think your pattern is close, but I would use this:
/^(?=.*[0-9])[a-z0-9]{4,12}$/i
The only lookahead you need is one which asserts that there is a single number. There is no requirement for there to be any letters, so don't bother adding an assertion for that. Then, match any alphanumeric character 4 to 12 times.
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('abc'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('123'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('abcd'));
console.log(/^(?=.*[0-9])[a-z0-9]{4,12}$/i.test('Abc1'));

Regex - match range of characters with a quantifier that only matches numbers

I've found a similar question on SO, but nothing I can get my head around. Here's what I need;
6 or more digits, with these characters allowed \s\-\(\)\+
So here's what I have /^[0-9\s\-\(\)\+]{6,}$/
The problem is, I don't want anything other than the number to count towards the 6 or more quantifier. How can I only "count" the digits? It would also been good if I could stop those other allowed characters from being entered adjacently e.g:
0898--234
+43 34 434
After an hour of reading up and looking at a regex cheat sheet, I'm hoping some kind person can point me in the right direction!
You could do something like this:
/^([\s()+-]*[0-9]){6,}[\s()+-]*$/
This will match any number of special characters (whitespace, parentheses, pluses or hyphens) followed by a single decimal digit, repeated 6 or more times, followed by any number of special characters.
Or this if you don't want to match two or more adjacent special characters:
/^([\s()+-]?[0-9]){6,}[\s()+-]?$/
You can use lookahead:
/^(?=(\D*\d){6,})[0-9\s()+-]{6,}$/
/^[\s()+-]*(\d[\s()+-]*){6,}$/
This doesn't count the 'cruft'. It allows any number of special characters, followed by six times [a digit followed by any number of special characters].
If you want max. one special character in between digits, use ? instead of *, but I assume you don't care much for more than one special character at the start or at the end, so I'd go with
/^[\s()+-]*(\d[\s()+-]?){6,}[\s()+-]*$/
This matches any number of special characters, followed by 6 or more times [a digit followed by at most one special character], followed by any number of special characters.
Another option would be to strip your special characters from the string first, and then match against 6 or more digits.
var rawInput = " 12 (3) -- 4 -5 ++6";
var strippedInput = rawInput.replace(/[\s()+-]*/g, "");
return new RegExp("^\d{6,}$").test(strippedInput);
Remember that you have a complete programming language at your disposal. I've noticed people tend to decide they need to use regex and then forget about everything else they can do.

JavaScript RegExp to match a (partial) hour

I want to allow people to enter times into a textbox in various formats. One of the formats would be either:
2h for 2 hours, or
2.5h for 2 and a half hours
I want to use a regex to recognise the pattern but it's not picking it up for some reason:
I have:
var hourRegex = /^\d{1,2}[\.\d+]?[h|H]$/;
which works for 2h, but not for 2.5h.
I thought that this regex would mean - Start at the beginning of the string, have one or two digits, then have none or one decimal points which if present must be followed by one or more digits then have a h or a H and then it must be the end of the string.
I have tried the regex tool here but no luck.
/^\d{1,2}(?:\.\d+)?h$/i; Use parentheses instead of square braces.
Start at the beginning
One or two digits
Optional: a dot followed by at least one digit
End with a h
Case insensitive
RegExp tuturial
[...] - square braces mean: anything which is within the provided range.
[^...] means: Match a character which is not within the provided range
(...) - parentheses mean: Group me. Optionally, the first characters of a group can start with:
?: - Don't reference me (me, I = group)
?= - Don't include me in the match, though I have to be here
?! - I may not show up at this point
{a,b}, {a,} means: At least a, maximum b characters. Omitting b = Infinity
+ means: at least one time, match as much as possible equivalen to {1,}
* means: match as much as possible equivalent to {0,}
+? and *? have the same effect as previously described, with one difference: Match as less as possible
Examples
[a-z] One character, any character between a, b, c, ..., z
(a-z) Match "a-z", and group it
[^0-9] Match any non-number character
See also
MDN: Regular Expressions - A more detailed guide
The trouble is here :
[\.\d+]
you can not use character classes inside brackets.
Use this instead:
(\.[0-9]+)?
You've confused your square brackets with your parenthesis. Square brackets look for a single match of any contained character, whereas parenthesis look for a match of the entire enclosed pattern.
Your issue lies in [\.\d+]? It's looking for . or 0-9 or +.
Instead you should try:
/^\d{1,2}(\.\d+)?(h|H)$/
Although that will still allow users to enter invalid numbers, such as 99.3 which is probably not the expected behavior.

Categories

Resources