RegEx - contain specific number after period - javascript

I have strings similar to; First Half Goals 1.5/2. The text at the beginning can be anything so cannot depend on that as part of the RegEx as it varies. What I want to do is to match the number sequence at the end. Test samples would be:
5
0.5/1
2.5/3
147
The sequence can either contain a slash or it cannot. If it contains a slash, there must be a value after it - either integer or decimal. The value before the decimal (if one is present) can be any number of digits - \d+ - but the value after should must be 0 or 5 - (0|5). The 1st value before the slash (/) is either an integer or a decimal. If the sequence contains a slash, then the number after is also either a integer or a decimal. All values are positive.
The main point of this RegEx is that I need it to only match once. The was the RegEx I was using:
(\d(\.(0|5))?\/\d(\.(0|5)))|(\d\.(0|5))|(\d)
The issue with the regex above is that the example string I use; First Half Goals 1.5/2 matched twice. Once on the 1.5 & the 2nd on the 2. I have now altered it to be this:
\d+(\.(0|5))?(\/?\d+(\.(0|5))?)?
This is slightly better but if I give the test sample; 1.6/2, it will match 6/2. This will be because the decimal section on the former number is optional. I'm not sure if a lookbehind would come in handy here, I don't have much experience with them. Sadly the text beforehand is so unpredictable otherwise I could trim the string to only get the wanted substring & then match from the start of the string but can't do that. An outline of what should match & what should not:
1 // Match
5.5 // Match
7.8 // No Match
0/0.5 // Match
147/147.5 // Match
2. // No Match
6.5/ // No Match
7.0/8 // Match
10.0 // Match
1./2.5 // No Match
5./6 // No Match
/157 // No Match
/4.5 // No Match
I've tried to explain as best I could but if you need more details then I'll provide them

In Node.js, RegExp supports lookbehinds and you may use
/\b(?<!\d\.|\/)\d+(?:\.[05])?(?:\/\d+(?:\.[05])?)?$/
See the regex demo
Details
\b - word boundary
(?<!\d\.|\/) - no digit + dot or a slash are allowed immediately to the left of the current location
\d+ - one or more digits
(?:\.[05])? - an optional sequence of
\. - a dot
[05] - 0 or 5
(?:\/\d+(?:\.[05])?)? - an optional sequence of
\/\d+ - a / and 1+ digits
(?:\.[05])? - an optional sequence of a dot and then 0 or 5
$ - end of string.

Related

Limit 10 characters is numbers and only 1 dot

I'm having a regex problem when input
That's the requirement: limit 10 characters (numbers) including dots, and only 1 dot is allowed
My current code is only 10 characters before and after the dot.
^[0-9]{1,10}\.?[0-9]{0,10}$
thank for support.
You could assert 10 chars in the string being either . or a digit.
Then you can match optional digits, and optionally match a dot and again optional digits:
^(?=[.\d]{10}$)\d*(?:\.\d*)?$
The pattern matches:
^ Start of string
(?=[.\d]{10}$) Positive lookahead, assert 10 chars . or digit till the end of string
\d* Match optional digits
(?:\.\d*)? Optionally match a `. and optional digits
$ End of string
See a regex demo.
If the pattern should not end on a dot:
^(?=[.\d]{10}$)\d*(?:\.\d+)?$
Regex demo
The decimal point throws a wrench into most single pattern approaches. I would probably use an alternation here:
^(?:\d{1,10}|(?=\d*\.)(?!\d*\.\d*\.)[0-9.]{2,11})$
This pattern says to match:
^ from the start of the number
(?:
\d{1,10} a pure 1 to 10 digit integer
| OR
(?=\d*\.) assert that one dot is present
(?!\d*\.\d*\.) assert that ONLY one dot is present
[0-9.]{2,11} match a 1 to 10 digit float
)
$ end of the number
You can use a lookahead to achieve your goals.
First, looking at your regex, you've used [0-9] to represent all digit characters. We can shorten this to \d, which means the same thing.
Then, we can focus on the requirement that there be only one dot. We can test for this with the following pattern:
^\d*\.?\d*$
\d* means any number of digit characters
\.? matches one literal dot, optionally
\d* matches any number of digit characters after the dot
$ anchors this to the end of the string, so the match can't just end before the second dot, it actually has to fail if there's a second dot
Now, we don't actually want to consume all the characters involved in this match, because then we wouldn't be able to ensure that there are <=10 characters. Here's where the lookahead comes in: We can use the lookahead to ensure that our pattern above matches, but not actually perform the match. This way we verify that there is only one dot, but we haven't actually consumed any of the input characters yet. A lookahead would look like this:
^(?=\d*\.?\d*$)
Next, we can ensure that there are aren't more than 10 characters total. Since we already made sure there are only dots and digits with the above pattern, we can just match up to 10 of any characters for simplicity, like so:
^.{1,10}$
Putting these two patterns together, we get this:
^(?=\d*\.?\d*$).{1,10}$
This will only match number inputs which have 10 or fewer characters and have no more than one dot.
If you would like to ensure that, when there is a dot, there is also a digit accompanying it, we can achieve this by adding another lookahead. The only case that meets this condition is when the input string is just a dot (.), so we can just explicitly rule this case out with a negative lookahead like so:
(?!\.$)
Adding this back in to our main expression, we get:
^(?=\d*\.?\d*$)(?!\.$).{1,10}$

How to implement negative null floating point regex

What could I use as a regex that validates floating point numbers?
The numbers could be negative and cannot start by 0 (unless it is a real 0, or a 0 followed by decimal points such in 0.00123)
On the other hand, the regex should validate partial/uncompleted numbers. For example:
''(empty string) is valid
- is valid (it could still be a valid number with appropiate user input)
0 is valid (as 0.1 could be valid)
0.0 is valid, for the same previous reason
-0.000 is valid
-01 is not valid
.2 is not valid
I tried with this regexp:
^(-|-?0\.?[0-9]*|-?[1-9][0-9]*\.?[0-9]*|)$
It allows me to discard all non-numeric values ​​and still allow fractional values, but how to implement the possibility that the user cannot enter numbers in the format -0232, but can enter -0.232
If I get it right, you want a regex that validates "could-be-a-future-decimal" numbers. So (empty string) -, -0, 0 and 0.... should be valid.
You may use this regex:
^-?(?:(?!0\d)\d+\.?\d*)?$
You have a demo here.
Explained:
^ # Start of string
-? # an optional minus
(?: # non-capturing group
(?!0\d) # whatever comes next, it cannot be 0 + number
\d+ # at least one number
\.? # optional dot
\d* # any quantity of numbers
)? # previous group is optional
$
Also, bear in mind that the previous thing is a regex object. So you should try to use it like this in javascript:
/myregex/
However, javascript also allows using string-based regexes (which by your comments it seems that is what you want...)
In that case you can use the new RegExp syntax. However, bear in mind that since you'll be using a string, you need to scape any characters a string should scape.
For example, you may use:
function return_some_regex_string() {
// NOTE backslashes had to be scaped since this is a string,
// not a real regex object
return '^-?(?:(?!0\\d)\\d+\\.?\\d*)?$';
}
console.log("0.123".match(new RegExp(return_some_regex_string())));
console.log("-03233".match(new RegExp(return_some_regex_string())));
console.log("333-3334".match(new RegExp(return_some_regex_string())));
But, at the same time, you could already return the regex object, which seems a simpler way to work than using string-based regexes:
function return_some_regex() {
return /^-?(?:(?!0\d)\d+\.?\d*)?$/;
}
console.log("0.123".match(return_some_regex()));
console.log("-03233".match(return_some_regex()));
console.log("333-3334".match(return_some_regex()));
You could match an optional hyphen, followed by either a floating point or match a number starting with 1-9
^-?(?:\d+\.\d+|[1-9]\d*|0\.?)$
The pattern will match
^ Start of string
-? Optional hyphen
(?: Non capture group
\d+\.\d+ Match 1+ digits, dot and 1+ digits
| Or
[1-9]\d* Match a digit 1-9 and 0+ digits 0-9
| Or
0\.? Match a zero and optional dot
) Close group
$ End of string
Regex demo
let pattern = /^-?(?:\d+\.\d+|[1-9]\d*|0\.?)$/;
["-0123",
"0123123",
"-03123123",
"1234",
"-0.234",
"0.4",
"0.3312312",
"1",
"-1234",
"0",
"0."
].forEach(s => console.log(`${s} match:${pattern.test(s)}`));
If you want to match an empty string or just a single hyphen, you can also make the second part optional.
^-?(?:\d+\.\d+|[1-9]\d*|0\.?)?$
Regex demo

how to accept negative values for amount textfield with this regular expression

I want to accept a negative value to the text field by without disturbing the functionality for following regular expression :
(?!^0*$)(?!^0*[.]0*$)^[0-9]{1,8}([.][0-9]{1,2})?$
for ex : -12.12, -1223233.23, -32323.32
Thanks.
Your regex has lookaheads that are each triggering at every location inside a string. To make the regex more efficient and easily adjustable for a fix like the one you need, you need to move the ^ out of the lookaheads: ^(?!0*$)(?!0*[.]0*$)^[0-9]{1,8}([.][0-9]{1,2})?$.
Now, you need to add an optional minus at the start. "Optional" means 1 or 0 occurrences. In JavaScript, you can use a ? quantifier for that (in POSIX BRE, you would have no other alternative but \{0,1\}).
So, use
^-?(?!0*$)(?!0*[.]0*$)[0-9]{1,8}([.][0-9]{1,2})?$
See the regex demo
The regex breakdown:
^ - start of string
-? - 1 or 0 hyphens
(?!0*$) - make sure there are no zeros up to the end of string (return no match if a zero is found)
(?!0*[.]0*$) - make sure there are no zeros + a dot + zeros up to the end of string
[0-9]{1,8} - match 1 to 8 digits
([.][0-9]{1,2})? - 1 or 0 sequences of...
[.] - a literal dot
[0-9]{1,2} - 1 to 2 digits
$ - end of string.
Just add -? to make the negative sign optional, or simply - if it's mandatory.
(?!^-?0*$)(?!^-?0*[.]0*$)^-?[0-9]{1,8}([.][0-9]{1,2})?$
Edit: Fixed
THis validates an integer (positive or negative)
^-{0,1}\d+$
This validate a decimal number (positive or negative)
^-{0,1}\d*\.{0,1}\d+$

Possible to make regular expression with sub-query

I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:
Starts with 07
Contains only numbers, whitespace or dashes
Contains exactly 11 numbers
Is this possible to do in just one regular expression and if so, how please?
I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
//string matches conditions
}
Explanation of the regex:
^: Anchor that means "match start of string".
07: Match the string 07. Together with the above, it means that the string must start with 07.
[: Beginning of a character class i.e., a set of characters that we want to allow
\d: Match a digit (equivalent to 0-9).
\-:
" ": Match whitespace (markdown doesn't let me show a single space as code)
]: End of character class.
+: One or more of the previous.
$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.
So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.
Since #Vivin throws out the challenge :
/^07([-\s]*\d){9}[-\s]*$/
^07 : begin with digits 07
( : start group
[-\s]* : any number of - or whitespace
\d : exactly one digit
){9} : exactly 9 copies of this group (11 digits including 07)
[-\s]* : optional trailing spaces or -
$ : end of string
Of course a more useful way might be as follows
if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
....
}
which has the advantage (?) of leaving just the digits in telNo
Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}
This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
() - include in capture
(?:) - do not include in capture
\s - whitespace
| - or
- - dash
* - zero or more
\d - digits only
{9} - exactly nine of what is captured

Regular expression for number with length of 4, 5 or 6

I need a regular expression that validate for a number with length 4, 5, 6
I used ^[0-9]{4} to validate for a number of 4, but I do not know how to include validation for 5 and 6.
Try this:
^[0-9]{4,6}$
{4,6} = between 4 and 6 characters, inclusive.
[0-9]{4,6} can be shortened to \d{4,6}
Be aware that, as written, Peter's solution will "accept" 0000. If you want to validate numbers between 1000 and 999999, then that is another problem :-)
^[1-9][0-9]{3,5}$
for example will block inserting 0 at the beginning of the string.
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000 is valid, then it becomes more complex. If we use look-ahead then we can write something like
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$), then skips the 0s 0*and search for a non-zero [1-9] followed by at least 3 digits [0-9]{3,}.
If the language you use accepts {}, you can use [0-9]{4,6}.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?.
To match standalone 4-6-digit numbers, you may use
^\d{4,6}$ // If full string match is expected
\b\d{4,6}\b // If no letters/digits/underscores are expected on both ends
(?<!\d)\d{4,6}(?!\d) // If no digits are expected on both ends, but letters/_ are allowed
(^|\D)(\d{4,6})(?!\d) // Same as above, in case lookbehinds are not supported (get Group 2 value)
See Regex #1 - Regex #2 - Regex #3 and Regex #4 demos.
Details:
^ - start of string
\b - a word boundary
(?<!\d) - a negative lookbehind that fails the match if there is a digit immediately to the left of the current location
(^|\D) - a capturing group matching either start of string or a non-digit char
\d{4,6} - four, five or six digits
(?!\d) - a negative lookahead that fails the match if there is a digit immediately to the right of the current location
$ - end of string

Categories

Resources