Regular expression for opposite of integer without leading zeros - javascript

I have a regex for integers with leading zero and it works fine. I am using it like:
value = value.replace(/[^0-9]/, '');
Now, I want another regex for integers without leading zero. So, I got the below mentioned regex from stackoverflow answer:
[1-9]+[0-9]*
As I am using string.replace, I have to invert the regex. So my final code looks like:
value = value.replace(/^(?![1-9]+[0-9]*)$/, '');
But now resulting value is always empty.
Expectations:
User should be allowed to typein these examples:
123456
123
78
User should not be able to type in these characters:
0123
e44
02565
asdf
02asf
754ads
Also, if I get a regex for only decimals without leading 0 and no e and should work in value.replace, then it will be a bonus for me.
I don't know how to construct regex patterns. So, if this a very basic question, then please forgive me.

Try
value = "e044".replace(/^.*?([1-9]+[0-9]*).*$/, '$1');
return 44

I would do it in two steps.
First remove the leading part (remove anything which is not a 1-9 at the beginning)
value = value.replace(/^[^1-9]*/, '');
then remove the trailing parts (match any number(s) in the beginning and remove the rest)
value = value.replace(/(?![0-9]+).*/, '');
for decimals use this (credits drkunibar):
value = value.replace(/.*?([1-9]+[0-9]*[\.]{0,1}[0-9]*).*/,'$1');

Please try this:
match = /^[1-9]\d*$/.test(value);
match will contain a boolean,true if the user enters a number without 0 in the lead,false-for anything other than number without 0 in the lead.

Related

Match floats but not dates separated by dot

I'm trying to build a regex which can find floats (using a dot or comma as decimal separator) in a string. I ended up with the following:
/([0-9]+[.,]{1}[0-9]+)/g
Which seems to work fine expect that it matches dates separated by . as well:
02.01.2000 // Matches 12.34
I've tried ([0-9]+[.,]{1}[0-9]+)(?![.,]) but that does not work as I expected it :)
How would I omit the date case, but still pass the following scenarios:
I tried some stuff 12.23
D12.34
12.34USD
2.3%
12,2
\n12.1
You can use this regex using alternation:
(?:\d+\.){2}\d+|(\d+[.,]\d+)
and extract your matches from captured group #1.
This regex basically matches and discards date strings on LHS of alternation and then matches and captures floating numbers on RHS of alternation.
RegEx Demo
Code:
const regex = /(?:\d+\.){2}\d+|(\d+[.,]\d+)/gm;
const str = `I tried some stuff 12.23
D12.34
12.34USD 02.01.2000
2.3%
12,2 02.01.2000
\\n12.1`;
let m;
let results = [];
while ((m = regex.exec(str)) !== null) {
if (m[1])
results.push( m[1] );
}
console.log(results);
You want to make sure that it isn't surrounded with more ",." or numbers. Is that right?
/[^,.0-9]([0-9]+[.,]{1}[0-9]+)[^,.0-9]/g
Given the following:
hi 1.3$ is another 1.2.3
This is a date 02.01.2000
But this 5.30USD is a number.
But a number at the end of a sentance 1.7.
Or a number comma number in a list 4,3,4,5.
It will match "1.3" and "5.30"
Using #anubhava's example (?:\d+\.){2}\d+|(\d+[.,]\d+) You get the following result:
It will match "1.3", "5.30", "1.7", "4,3", and "4,5"
Moral of the story is you need to think through all the possible scenarios and understand how you want to treat each scenario. The last line should be a list of 4 numbers. But is "4,3" by itself two separate numbers or from a country where they use commas to denote decimal?

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))

Regex for country code

I'm trying to write a regex for country code, which should limit to four characters maximum, only symbol allowed is a + sign. When the + is used, the + has to be in the beginning, and it should have at least one number.
Valid cases
+1
1
+12
12
+123
1234
Invalid cases
+
+1234
12345
1+
12+
<empty>
etc.
The expression that I have right now.
/(\+\d{1,3})/
Can it be more elegant?
-Thank you in advance!!
This should work. I used
/^(\+?\d{1,3}|\d{1,4})$/
See results
Edit:
The //gm flags are global and multiline, respectively. You need those if you have a string that can have multiple places to match a country code, or there are multiple lines in your string. If your string is going to be more than just a possible country code, you'd need to get rid of the ^ and $ at the beginning and end of the regex. To use the regex, you'd want something like this:
var regex = /^(\+?\d{1,3}|\d{1,4})$/gm
var str = "+123"
var match = str.match(regex);
//match is an array, with one result in this case. So match[0] == "+123"
You need to make a case differentiation. Either with or without leading plus sign:
(\+\d{1-3})|(\d{1,4})
Whether you want to anchor the expression to line limits (^ and $) or check for leading or trailing white spaces or the like obviously depends on your situation.
country codes can be of following types
+1
+91
+223
+1-224
The javascript regex that makes sure that the input is one if the
/^\+(\d{1}\-)?(\d{1,3})$/
I prepared this according to wikipedia article, for parsing correct information for 1 or 2 digit country codes this is much more efficient, but needs improvement for subterritories if you need them;
(?:\+|00)(1|7|2[07]|3[0123469]|4[013456789]|5[12345678]|6[0123456]|8[1246]|9[0123458]|(?:2[12345689]|3[578]|42|5[09]|6[789]|8[035789]|9[679])\d)

JavaScript and regular expressions: get the number of parenthesized subpattern

I have to get the number of parenthesized substring matches in a regular expression:
var reg=/([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g,
nbr=0;
//Some code
alert(nbr); //2
In the above example, the total is 2: only the first and the last couple of parentheses will create grouping matches.
How to know this number for any regular expressions?
My first idea was to check the value of RegExp.$1 to RegExp.$9, but even if there are no corresponding parenthseses, these values are not null, but empty string...
I've also seen the RegExp.lastMatch property, but this one represents only the value of the last matched characters, not the corresponding number.
So, I've tried to build another regular expression to scan any RegExp and count this number, but it's quite difficult...
Do you have a better solution to do that?
Thanks in advance!
Javascripts RegExp.match() method returns an Array of matches. You might just want to check the length of that result array.
var mystr = "Hello 42 world. This 11 is a string 105 with some 2 numbers 55";
var res = mystr.match(/\d+/g);
console.log( res.length );
Well, judging from the code snippet we can assume that the input pattern is always a valid regular expression, because otherwise it would fail before the some code partm right? That makes the task much easier!
Because We just need to count how many starting capturing parentheses there are!
var reg = /([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g;
var nbr = (' '+reg.source).match(/[^\\](\\\\)*(?=\([^?])/g);
nbr = nbr ? nbr.length : 0;
alert(nbr); // 2
And here is a breakdown:
[^\\] Make sure we don't start the match with an escaping slash.
(\\\\)* And we can have any number of escaped slash before the starting parenthes.
(?= Look ahead. More on this later.
\( The starting parenthes we are looking for.
[^?] Make sure it is not followed by a question mark - which means it is capturing.
) End of look ahead
Why match with look ahead? To check that the parenthes is not an escaped entity, we need to capture what goes before it. No big deal here. We know JS doens't have look behind.
Problem is, if there are two starting parentheses sticking together, then once we capture the first parenthes the second parenthes would have nothing to back it up - its back has already been captured!
So to make sure a parenthes can be the starting base of the next one, we need to exclude it from the match.
And the space added to the source? It is there to be the back of the first character, in case it is a starting parenthes.

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