I want to validate a text field to accept just text like this :
1,2;2,3;1-3
1-2;4;2,3;4;1-3
12
I don't want the types like this :
;1
,1
-1
1;;2
1,,2
1--2
1-2-3
1,2,3
1,2-3
so I make this regular expression but it seems doesn't work like what I want
var reg = /^\d*(((?!.*--)(?!.*,,)(?!.*;;)(?!.*,;)(?!.*,-)(?!.*-;)(?!.*-,)(?!.*;,)(?!.*;-))[,-;])*\d$/
thanks for your help :)
you can simply use the regex
function match(str){
return str.match(/^(?!.*([-,])\d+\1)(?!.*,\d+-)\d+(?:[-,;]\d+)*$/) != null
}
console.log(match(';1'));
console.log(match(',1'));
console.log(match('1;;2'));
console.log(match('1-3'));
console.log(match('12'));
console.log(match('1,2;2,3;1-3'));
console.log(match('1-2;4;2,3;4;1-3'));
console.log(match('1,2,3'));
take a look at regex demo
Here's my attempt. Based on your examples I've assumed that semi-colons are used to separate 'ranges', where a 'range' can be a single number or a pair separated by either a comma or a hyphen.
var re = /^\d+([,\-]\d+)?(;\d+([,\-]\d+)?)*$/;
// Test cases
[
'1',
'1,2',
'1-2',
'1;2',
'1,2;2,3;1-3',
'1-2;4;2,3;4;1-3',
'12',
';1',
',1',
'-1',
'1;;2',
'1,,2',
'1--2',
'1-2-3',
'1,2,3',
'1,2-3'
].forEach(function(str) {
console.log(re.test(str));
});
The first part, \d+([,\-]\d+)? matches a 'range' and the second part (;\d+([,\-]\d+)?)* allows further 'ranges' to be added, each starting with a semi-colon.
You can add in ?: to make the groups non-capturing if you like. That's probably a good idea but I wanted to keep my example as simple as I could so I've left them out.
You may use
/^\d+(?:(?:[-,;]\d+){3,})?$/
See the regex demo
Details
^ - start of string
\d+ - 1 or more digits
(?:(?:[-,;]\d+){3,})? - 1 or 0 sequences of:
(?:[-,;]\d+){3,} - 3 sequences of:
[-,;] - a -, , or ;
\d+ - 1 or more digits
$ - end of string
var ss = [ '1,2;2,3;1-3','1-2;4;2,3;4;1-3','12',';1',',1','-1','1;;2','1,,2','1--2','1-2-3','1,2,3','1,2-3',';1',',1','-1','1;;2','1,,2','1--2' ];
var rx = /^\d+(?:(?:[-,;]\d+){3,})?$/;
for (var s of ss) {
console.log(s, "=>", rx.test(s));
}
NOTE: the [,-;] creates a range between , and ; and matches much more than just ,, - or ; (see demo).
Related
I'm struggling with finding the correct RegExp to match number with plus (+) or minus (-) sign at the end.
I have a select list of number ranging from 0.00- to 40.00- and 0.00+ to 40.00-. I'm using the following RegExp to filter out non matching records:
$("#MySelectBox").change(function() {
var filter = $(this).val()
// If the list item does not contain the numbers phrase fade it out
if ($(this).text().search(new RegExp('\\b'+filter+'\\b', "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
However, it will show both + and - numbers. For example: if filter = 3.00+ then it will return both 3.00+ and 3.00- values.
Any ideas how to get the exact match?
[\+-]\d{1,2}\.00
Will match + or -, followed by one or two digits (\d{1,2}), followed by .00.
However, RegExes don't have "greater than 40" kind of logic. They only match patterns.
There are useful tools to help you, like Rexegpal
So with your brief:
Check string matches pattern: "+xx.xx" or "-xx.xx"
Only numbers between -40 or +40
Omit results out of bounds
This could be a good way to achieve your desired result.
Notes: (1) Unsure if you wanted to enforce the demical point, (2) there are certainly multiple ways to achieve your result, this is is just one.
const regex = /^[\-\+]\d+\.*\d*$/;
const tests = ["41", "20", "+20", "-20", "+20.00", "-20.20", "20.20"];
const passedTests = tests.filter(number => {
const parsedNumber = Number.parseFloat(number);
const isValid = !!number.match(regex) && parsedNumber > -40 && parsedNumber < 40;
console.log(`Test ${number}, result: ${isValid}`);
return isValid;
});
console.log(passedTests);
To get an exact match for a number with plus (+) or minus (-) sign at the end and from 0.00- to 40.00- and 0.00+ to 40.00+, you can use:
^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$
^ Start of string
(?: Non capture group for the alternation |
(?:[0-9]|[123]\d) Match either a digit 0-9 or a number 10 - 39
\.\d\d Match a . and 2 digits 0-9
| Or
40\.00 Match 40.00
) Close group
[+-] Match either + or -
$ End of string
Regex demo
In Javascript you can use
const regex = /^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$/;
If the value is not the only value in the string, you could start with pattern with a word boundary \b and assert a whitespace boundary at the right (?!\S)
\b(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-](?!\S)
Regex demo
I am trying to put together a regex that would extract me the surface from the below strings, excluding the values that are preceded with Japanese characters.
"110.94m2・129.24m2"; --> 110.94m2 and 129.24m2
"81.95m2(24.78坪)、うち2階車庫8.9m2" --> 81.95m2
"80.93m2(登記)" --> 80.93m2
"93.42m2・93.85m2(登記)" --> 93.42m2 and 93.85m2
"81.82m2(実測)" --> 81.82m2
"81.82m2(実測)、うち1階車庫7.82m2" --> 81.82m2
"90.11m2(実測)、うち1階車庫8.07m2" --> 90.11m2
So far I have put together the following regex, however not working in every case.
(?<![\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF])([0-9\.]*m2)
ie. the following string yields: 81.95m2 and .9m2. I would need only 81.85m2.
"81.95m2(24.78坪)、うち2階車庫8.9m2"
Would you know how to treat the following block of the negative look ahead as an exclusion?
Thank you
You need to cancel any match if preceded with a digit or digit + period.
Add (?<!\d)(?<!\d\.) after or before the first lookbehind:
(?<![\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF])(?<!\d)(?<!\d\.)(\d+(?:\.\d+)?m2)
See the regex demo
The (?<!\d) is a negative lookbehind that fails the match if there is a digit immediately to the left of the current location and (?<!\d\.) fails when there is a digit and a dot right before.
The \d+(?:\.\d+)? is a more precise pattern to match numbers like 30 or 30.5678: 1 or more digits followed with an optional sequence of . and 1+ digits.
NOTE that this regex will only work with the ES2018+ JS environments (Chrome, Node). You may capture an optional Japanese char into Group 1 and the number into Group 2, then check if Group 1 matched and if yes, fail the match, else, grab Group 2.
The regex is
/([\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF])?(\d+(?:\.\d+)?m2)/g
See usage example below.
JS ES2018+ demo:
const lst = ["110.94m2・129.24m2", "81.95m2(24.78坪)、うち2階車庫8.9m2", "80.93m2(登記)", "93.42m2・93.85m2(登記)", "81.82m2(実測)" , "81.82m2(実測)、うち1階車庫7.82m2", "90.11m2(実測)、うち1階車庫8.07m2"];
const regex = /(?<![\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF])(?<!\d)(?<!\d\.)(\d+(?:\.\d+)?m2)/g;
lst.forEach( s =>
console.log( s, '=>', s.match(regex) )
);
console.log("Another approach:");
lst.forEach( s =>
console.log(s, '=>', s.match(/(?<![\p{L}\d]|\d\.)\d+(?:\.\d+)?m2/gu))
)
JS legacy ES versions:
var lst = ["110.94m2・129.24m2", "81.95m2(24.78坪)、うち2階車庫8.9m2", "80.93m2(登記)", "93.42m2・93.85m2(登記)", "81.82m2(実測)" , "81.82m2(実測)、うち1階車庫7.82m2", "90.11m2(実測)、うち1階車庫8.07m2"];
var regex = /([\u4E00-\u9FAF\u3040-\u3096\u30A1-\u30FA\uFF66-\uFF9D\u31F0-\u31FF])?(\d+(?:\.\d+)?m2)/g;
for (var i=0; i<lst.length; i++) {
var m, res =[];
while (m = regex.exec(lst[i])) {
if (m[1] === undefined) {
res.push(m[2]);
}
}
console.log( lst[i], '=>', res );
}
Variations
If you plan to match a float/int number with m2 after it that is only preceded with whitespace or at the start of the string use
(?<!\S)\d+(?:\.\d+)?m2
If you plan to match it when not preceded with any letter use
pcre java - (?<![\p{L}\d]|\d\.)\d+(?:\.\d+)?m2 (also works in JS ES2018+ environments: /(?<![\p{L}\d]|\d\.)\d+(?:\.\d+)?m2/gu)
python - (?<!\d\.)(?<![^\W_])\d+(?:\.\d+)?m2
Note you may add \b word boundary after 2 to make sure there is a non-word char after it or end of string.
I have problem with simple rexex. I have example strings like:
Something1\sth2\n649 sth\n670 sth x
Sth1\n\something2\n42 036 sth\n42 896 sth y
I want to extract these numbers from strings. So From first example I need two groups: 649 and 670. From second example: 42 036 and 42 896. Then I will remove space.
Currently I have something like this:
\d+ ?\d+
But it is not a good solution.
You can use
\n\d+(?: \d+)?
\n - Match new line
\d+ - Match digit from 0 to 9 one or more time
(?: \d+)? - Match space followed by digit one or more time. ( ? makes it optional )
let strs = ["Something1\sth2\n649 sth\n670 sth x","Sth1\n\something2\n42 036 sth\n42 896 sth y"]
let extractNumbers = str => {
return str.match(/\n\d+(?: \d+)?/g).map(m => m.replace(/\s+/g,''))
}
strs.forEach(str=> console.log(extractNumbers(str)))
If you need to remove the spaces. Then the easiest way for you to do this would be to remove the spaces and then scrape the numbers using 2 different regex.
str.replace(/\s+/, '').match(/\\n(\d+)/g)
First you remove spaces using the \s token with a + quantifier using replace.
Then you capture the numbers using \\n(\d+).
The first part of the regex helps us make sure we are not capturing numbers that are not following a new line, using \ to escape the \ from \n.
The second part (\d+) is the actual match group.
var str1 = "Something1\sth2\n649 sth\n670 sth x";
var str2 = "Sth1\n\something2\n42 036 sth\n42 896 sth y";
var reg = /(?<=\n)(\d+)(?: (\d+))?/g;
var d;
while(d = reg.exec(str1)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
console.log("****************************");
while(d = reg.exec(str2)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
Could anyone help me with this regular expression issue?
expr = /\(\(([^)]+)\)\)/;
input = ((111111111111))
the one I would need to be working is = ((111111111111),(222222222),(333333333333333))
That expression works fine to get 111111 from (input) , but not when there are also the groups 2222... and 3333.... the input might be variable by variable I mean could be ((111111111111)) or the one above or different (always following the same parenthesis pattern though)
Is there any reg expression to extract the values for both cases to an array?
The result I would like to come to is:
[0] = "111111"
[1] = "222222"
[2] = "333333"
Thanks
If you are trying to validate format while extracting desired parts you could use sticky y flag. This flag starts match from beginning and next match from where previous match ends. This approach needs one input string at a time.
Regex:
/^\(\(([^)]+)\)|(?!^)(?:,\(([^)]+)\)|\)$)/yg
Breakdown:
^\(\( Match beginning of input and immedietly ((
( Start of capturing group #1
[^)]+ Match anything but )
)\) End of CG #1, match ) immediately
| Or
(?!^) Next patterns shouldn't start at beginning
(?: Start of non-capturing group
,\(([^)]+)\) Match a separetd group (capture value in CG #2, same pattern as above)
| Or
\)$ Match ) and end of input
) End of group
JS code:
var str = '((111111111111),(222222222),(333333333333333))';
console.log(
str.replace(/^\(\(([^)]+)\)|(?!^)(?:,\(([^)]+)\)|\)$)/yg, '$1$2\n')
.split(/\n/).filter(Boolean)
);
You can replace brackes with , split it with , and then use substring to get the required number of string characters out of it.
input.replace(/\(/g, '').replace(/\)/g, '')
This will replace all the ( and ) and return a string like
111111111111,222222222,333333333333333
Now splitting this string with , will result into an array to what you want
var input = "((111111111111),(222222222),(333333333333333))";
var numbers = input.replace(/\(/g, '').replace(/\)/g, '')
numbers.split(",").map(o=> console.log(o.substring(0,6)))
If the level of nesting is fixed, you can just leave out the outer () from the pattern, and add the left parentheses to the [^)] group:
var expr = /\(([^()]+)\)/g;
var input = '((111111111111),(222222222),(333333333333333))';
var match = null;
while(match = expr.exec(input)) {
console.log(match[1]);
}
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");