Javascript Regex 1-10 - javascript

I am trying to get a regex that can get from 1-10 and i have been having trouble
I have tried :
/^[1-9]|10$/ //this will matches out 1-9 but not 10
/^10|[1-9]$/ //this will matches 10 but no 1-9 digits
I feel weird because i have seen this question before and people said either of these expression should work. Any ideas of another way to get any # from 1-10?

Assuming you want to match a string containing a number 1–10 and nothing else, you were close with /^[1-9]|10$/. The problem here is that the alternation | includes the ^ and $ characters, i.e. this expression will match either ^[1-9] (any string beginning with 1–9) or10$` (any string ending with 10). Parentheses solve this neatly:
/^([1-9]|10)$/
See it in action below:
const regex = /^([1-9]|10)$/gm; // `gm` flags for demo only; read below
const str = `1
2
3
4
foo
5
6
7
8
9
10`;
let m;
while (m = regex.exec(str)) {
console.log('Found match:', m[0]);
}
.as-console-wrapper{min-height:100%}
The snippet uses the g and m flags to find all of the matches across multiple lines. m makes ^ and $ match the beginning and end of each line rather than the beginning and end of the string. For your use case you probably don't want either flag.

Without knowing your specific use case, I don't see a reason to include ^ and & here, which requires that the number is surrounded by a start and end of line. Even if your inner regex was correct, it wouldn't match the '6' in: 'I have a 6 year old son.'
Instead, surround the inner regex with \b (a word boundary). So, to use Jordan's example, \b([1-9]|10)\b would match all numbers from 1-10. To use regex in javascript, you need to utilize one of several functions that accept it as an argument, or methods that can be called on it:
let regex = /\b([1-9]|10)\b/;
console.log('I have a 6 year old son.'.match(regex)[0]);
console.log('I have a six year old son.'.match(regex));
console.log('I have a 6 year old son.'.replace(regex, 'six'));
console.log(regex.test('I have a 6 year old son.'));
console.log(regex.test('I have a six year old son.'));

Related

Regular Expression question that include different letters

I am trying to figure out Regex that will only accept below strings.
7 and 8 numbers: '1234567' and '12345678'
7 and 8 numbers that start with T: 'T234567' and 'T2345678'
7 and 8 numbers that start with D: 'D234567' and 'D2345678'
7 and 8 numbers that start with TD: 'TD34567' and 'TD345678'
Regex I have is:
/^(T|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/
but it's not passing my unit test for 'D234567' and 'D2345678'
You could write the pattern as:
^(?:\d{7,8}|[TD]\d{6,7}|TD\d{5,6})$
Explanation
^ Start of string
(?: Non capture group for the alternatives
\d{7,8} Match 7-8 digits
| Or
[TD]\d{6,7} Match either T or D and 6-7 digits
| Or
TD\d{5,6} Match TD and 5-6 digits
) Close the non capture group
$ End of string
Regex demo.
I actually figure it out right after posted this question. Simply added |D after T| so like this.
/^(T|D|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/
const r = /^(?=.{7,8}$)T?D?\d+$/
is the simplest solution. Here's a breakdown of what happens:
import {lookAhead, maybe, sequence, suffix} from "compose-regexp"
const r = sequence(
// start anchor
/^/,
// are there exactly 7 or 8 characters before the end?
lookAhead(suffix([7,8], /./), /$/),
// optionally match a 'T'
maybe('T'),
// optionally match a 'D'
maybe('D'),
// match numbers until the end
suffix('+', /\d/),
/$/
)
You can try it out here
With tests aplenty.

Regex- match third character [duplicate]

This question already has answers here:
How to match all characters after nth character with regex in JavaScript?
(2 answers)
Closed 5 years ago.
For example, this is my string "RL5XYZ" and I want to check the third character is it 5 or some other number.
I would like to do this with the Regex, without substring.
If you're trying to check whether the third character of a string is a number, you can use the following regex:
/^..[0-9]/
^ Means the match must occur at the start of the string
. Means match any character (we do this twice)
[0-9] Means match a number character in the range 0-9. You can actually adjust this to be a different range.
You can also condense the . using the following notation
/^.{2}[0-9]/
The number in braces basically means repeat the previous operator twice.
You can also rewrite the character set [0-9] as \d.
/^.{2}\d/
To match in JS, simple call exec against the pattern you've created:
/^.{2}\d/.exec('aa3') // => ["aa3", index: 0, input: "aa3"]
/^.{2}\d/.exec('aaa') // => null
If its always going to be checking for the existence of two characters followed by a 5 which is then followed by something else then you could simply check
/..5*/
if you want to get the third character (assuming its always a digit) then you could use.
/..(\d)*/
You'll get results back from regEx like this:
Match 1
Full match 0-3 `RL5`
Group 1. 2-3 `5`
Match 2
Full match 3-5 `XY`
If you want to check if the third character is a digit you can use
.{2}\d.*
But . matches everything so maybe you prefer:
\w{2}\d\w*
\w{2} means any of this [a-zA-Z0-9_] two times.
\d means any digit
\w* means any of [a-zA-Z0-9_] zero or multiple times
var input = 'RL5XYZ';
var position = 3;
var match = '5';
position--;
var r = new RegExp('^[^\s\S]{'+position+'}'+match);
console.log(input.match(r));
position to check where is to find and match what to find
edit: I forgot a ^

Use regex to split a string at the first letter

I have a regex that can split a string at the first digit
var name = 'Achill Road Boy 1:30 Ayr'
var horsedata = name.match(/^(\D+)(.*)$/);
var horse = horsedata[1]; // "Achill Road Boy "
var meeting = horsedata[2]; // "1:30 Ayr"
However, I now need to further split
var meetingdata = meeting.match(?what is the regex);
var racetime = meetingdata[1]; // "1:30 "
var course = meetingdata[2]; // "Ayr"
What is the regex to split the string at the first letter?
You can use single regex to do that:
^([^\d]+) +(\d+):(\d+) (.*)$
It will catch name, hour and minute separately, and track name, in groups 1, 2, 3 and 4.
Note that I have added ^ and $ to the expression, meaning that this expression should match given string completely, from start to finish, which I think are useful safeguards against matching something inside the string which you didn't expect initially. They may, however, interfere with your task, so you can remove them if you don't need them.
When tinkering with regular expressions I always use this nifty tool, http://regex101.com - it has a very useful interface to debug regular expressions and also their execution time. Here's a link to a regular expression above: https://regex101.com/r/jYgc9K/1. It also gives you a nice clear breakdown of this regular expression:
Full match 0-24 `Achill Road Boy 1:30 Ayr`
Group 1. 0-15 `Achill Road Boy`
Group 2. 16-17 `1`
Group 3. 18-20 `30`
Group 4. 21-24 `Ayr`
Last, word of advice: there's a famous saying by Jamie Zawinski, a very smart guy. It goes like this:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems".
There's a lot of truth in this saying.
Given the string:
1:30 Ayr
The capture group from this regex will give you Ayr:
^[^a-zA-Z]*([a-zA-Z\s]+)$
Regular Expression Key:
^ - start of match
[^a-zA-Z]* - from 0 to any number of non-alphabet characters
([a-zA-Z\s]+) - capture group: from 1 to any number of alphabet characters and spaces
$ - end of match

Can you use a RegEx in javascript to see if a string contains a certain number of certain characters?

Say I am given a string (555)-555-5555, is there a way to check if the string contains exactly 10 occurrences of the number 5? I can think of other ways to solve this, but I am curious if this can be done with a regEx. I tried using
var re = new regExp(/5{10}/);
but apparently this only matches ten 5's in a row.
1) Delete all non-5, count the remains.
str.replace(/[^5]/g, '').length == 10
2) Count 5-with-a-tail groups:
str.match(/^[^5]*(?:5[^5]*){10}$/)
EDIT: fixed bugs. Also, the explanation: the entirety of the string (^...$) consists of any number of non-5, followed by exactly 10 groups of one 5 and any number of non-5. Thus,
x55pp5peep5o5555taco5lol5
breaks down into
^ start of string
[^5]* x
(?:5[^5]*){10} 5
5pp
5peep
5o
5
5
5
5taco
5lol
5
$ end of string
A "mostly" regex solution would be to match replace all other characters with the empty string and check the length of your result. Or similarly you could match and replace the character you want with the empty string and take the difference and see if it's the number you want.

Regular Expression for date validation - Explain

I was surfing online for date validation, but didn't exactly understand the regex. Can anyone explain it? I'm confused with ?, {} and $. Why do we need them?
dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
? means “zero or one occurences”.
{x} (where x is a number) means “exactly x occurences”
$ means “end of line”
These are very basic regex, I recommand you to read some documentation.
^ = beginning of the string
[0,1]? = optional zero, one or comma (the comma is probably an error)
\d{1} = exactly one digit (the {1} is redundant)
\/ = a forward slash
[0-2]? = optional zero, one or two (range character class) followed by any single digit (\d{1})
OR [3] = three (character class redundant here) followed by exactly one zero, one or comma
\/ = forward slash
[1]{1}[9]{1}[9]{1}\d{1} = 199 followed by any digit
OR 2-9 followed by any 3 digits
Overall, that's a really poorly written expression. I'd suggest finding a better one, or using a real date parser.
In Javascript you could validate date by passing it to Date.Parse() function. Successful conversion to a date object means you have a valid date.
Wouldn't recommend using regex for this. Too many edge cases and code gets hard to maintain.
? means "Zero or one of the aforementioned"
{n} means "exactly n of the aforementioned"
$ is the end of the String (Thanks #Andy E)
To summarize briefly:
`?' will match 0 or 1 times the pattern group you put in front of it. In this case, it's possibly being misused and should be left out, but it all depends on just what you want to match.
`{x}' tells the regex to match the preceding pattern group exactly x times.
`$' means to match the end of the line.
Well:
^ // start of the text
$ // end of the text
X{n} // number n inside these curly parenthesis define how many exact occurrences of X
X{m,n} // between m to n occurrences of X
X? // 0 or 1 occurrence of X
\d // any digits 0-9
For more help about Javascript date validation please see: Regular Expression to only grab date

Categories

Resources