Recursively patten js - javascript

I want to check a recursively text that verufy three rules.
1º: All the string should be a sequence of numbers between 0-31 + a dot .
Example: 1.23.5.12
2º: The string can't begin or end with a dot.
Like this.
.1.23.5.12.
3º You can write a max of 51 digits (following the previous rules)
I tried to make a pattern to my js function. But this dont work.
This is my function:
var str = document.getElementById("numero").value;
var patt1 = /^[0-9]+\./g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
What is wrong in the pattern?

You may use
/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/
See the regex demo
Details
^ - start of string
(?!(?:\D*\d){52}) - fail if there are 52 or more digits separated with any 0+ non-digits
(?:[12]?\d|3[01]) - 1 or 2 (optional) followed with any single digit or 3 followed with 0 or 1 (0 - 31)
(?:\.(?:[12]?\d|3[01]))* - zero or more consecutive repetitions of
\. - dot
(?:[12]?\d|3[01]) - see above (0 - 31)
$ - end of string.
Use it with test:
if (/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/.test(str)) {
// Valid!
}
Test:
var rx = /^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/;
var strs = [".12", "123", "1.23.5.12", "12345678"];
for (var s of strs) {
console.log(s, "=>", rx.test(s));
}

The regex ^[0-9]+\. matches from the start of the string ^ one or more digits [0-9]+ followed by a dot \.
You might use:
^(?!(\.?\d){52})(?:[0-9]|[12][0-9]|3[01])(?:\.(?:[0-9]|[12][0-9]|3[01]))+$
Explanation
^ Assert the start of the line
(?!(\.?\d){52}) Negative lookahead to assert that what follows is not 52 times an optional dot followed by one or more digits
(?:[0-9]|[12][0-9]|3[01]) Match a number 0 - 31
(?:\.(?:[0-9]|[12][0-9]|3[01]))+ Repeat in a group matching a dot followed by a number 0 - 31 and repleat that one or more times so that a single digit wihtout a dot does not match
$ Assert the end of the string
const strings = [
'1.23.5.12',
'1.23.5.12.',
'.1.23.5.12.',
'1.23.5.12',
'1',
'1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.2',
'1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12'
];
let pattern = /^(?!(\.?\d){52})(?:[0-9]|[12][0-9]|3[01])(?:\.(?:[0-9]|[12][0-9]|3[01]))+$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});

Related

jQuery: Unable to use RegExp to search for exactly "+3.00" or "-3.00"

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

JavaScript ReverseMatch

Is simple, i have this sentence:
str = "aeiou";
Need RegExp to scan string every X chars, but in reverse.
Example:
let every=2,
match = new RegExp(/>>RegExp Here<</gi);
//result "a ei ou"
Use
let str = "Hello world, 13th Mar 2020.";
let every=2;
let rx = new RegExp(`(?=(?:[^]{${every}})+$)`, 'g');
console.log(str.replace(rx, "_"));
// => H_el_lo_ w_or_ld_, _13_th_ M_ar_ 2_02_0.
The regex is /(?=(?:[^]{2})+$)/g, see the regex demo. It matches any location in the string that is followed with one or more repetitions of any two chars up to the string end, and inserts _ at that location.
Details
(?= - start of a positive lookahead:
(?:[^]{2}) - any char ([^] = [\s\S]), 1 or more times (thanks to +)
$ - end of string
) - end of the lookahead.

Regex: How to match digits not followed by any characters but allow characters after space?

Need help making a regex match with these criteria(pardon me for my possibly confusing phrasing).
Only match if starts with a number or dot
Match number, dot, and whitespace in between
Match until first space if nondigits follow that space
If only numbers follow the space then match it
If any characters except a dot, whitespace, or number follow a number then return null.
So far I've gotten this, but it still allows special characters to follow the numbers after.
/^[0-9\.][0-9\.\s]+(?!\w)/
Sample results
"1500" should return "1500"
"1500 0" should return "1500 0"
"1500 a" should return "1500"
"1500&" SHOULD return null, but so far returns "1500"
"1500a" should return null, as it should.
You may use
/^[\d.][\d\s.]*(?!\S)/
See the regex demo and the regex graph:
Details
^ - start of string
[\d.] - a digit or a dot
[\d\s.]* - 0 or more digits, whitespaces, dots, as many as possible
(?!\S) - followed with a whitespace or end of string.
JS demo:
var strs = ['1500 0', '1500 a', '1500&', '1500a'];
var rx = /^[\d.][\d\s.]*(?!\S)/;
for (var i=0; i < strs.length; i++) {
var m = strs[i].match(rx);
if (m) {
console.log(strs[i], "=>", m[0]);
} else {
console.log(strs[i], "=> NO MATCH");
}
}
You can try the following regex
^[\d\.][0-9\.]+((\s(?=\w)\d*)|$)
Explanation:
^ start of the string
[\d\.] match a char of number of digits or dot
[0-9\.]+ match any number of digits or dots
(\s(?=\w)\d*) match white space, look-ahead of alphanumeric chars and 0 or more occurrence of digits
|$ or end of the string if not match condition no 4.
JS Example:
let match = null, pattern = /^[\d\.][0-9\.]+((\s(?=\w)\d*)|$)/;
match = '1500 0'.match(pattern) || [null]
console.log(match[0])
match = '1500'.match(pattern) || [null]
console.log(match[0])
match = '1500&'.match(pattern) || [null]
console.log(match[0])
match = '1500 a'.match(pattern) || [null]
console.log(match[0])
match = '1500a'.match(pattern) || [null]
console.log(match[0])

Format and replace a string with a regular expression

I have a number that's at least 7 digits long.
Typical examples: 0000123, 00001234, 000012345
I want to transform them so that they become respectively:
01:23, 12:34, 23:45
Which mean replacing the whole string by the last 4 characters and putting a colon in the middle.
I can get the last 4 digits with (\d{4})$
And I can get 2 groups with this: (\d{2})(\d{2})$
With the last option, on a string 0000123 $1:$2 match gives me 00001:23
where I want 01:23
I replace the string like so:
newVal = val.replace(/regex/, '$1:$2');
You need to match the beginning digits with \d* (or with just .* if there can be anything):
var val = "0001235";
var newVal = val.replace(/^\d*(\d{2})(\d{2})$/, '$1:$2');
console.log(newVal);
Pattern details:
^ - start of string
\d* - 0+ digits (or .* will match any 0+ chars other than line break chars)
(\d{2}) - Group 1 capturing 2 digits
(\d{2}) - Group 2 capturing 2 digits
$ - end of string.
As Alex K. said, no need for a regular expression, just extract the parts you need with substr:
val = val.substr(-4, 2) + ":" + val.substr(-2);
Note that when the starting index is negative, it's from the end of the string.
Example:
function update(val) {
return val.substr(-4, 2) + ":" + val.substr(-2);
}
function test(val) {
console.log(val + " => " + update(val));
}
test("0000123");
test("0001234");
test("000012345");
You could throw the first characters away and the replace only the last matched parts.
console.log('00000001234'.replace(/^(.*)(\d{2})(\d{2})$/, '$2:$3'));
Use this regex: ^(\d+?)(\d{2})(\d{2})$:
var newVal = "0000123".replace(/^(\d+?)(\d{2})(\d{2})$/, '$2:$3');
console.log(newVal);

What will be the regular expression for below requirement in javascript

Criteria:
any word that start with a and end with b having middle char digit. this word should not be on the line which start with char '#'
Given string:
a1b a2b a3b
#a4b a5b a6b
a7b a8b a9b
Expected output:
a1b
a2b
a3b
a7b
a8b
a9b
regex: ?i need it for javascipt.
So far tried below thing:
var text_content =above_mention_content
var reg_exp = /^[^#]?a[0-9]b/gmi;
var matched_text = text_content.match(reg_exp);
console.log(matched_text);
Getting below output:
[ 'a1b', ' a7b' ]
Your /^[^#]?a[0-9]b/gmi will match multiple occurrences of the pattern matching the start of line, then 1 or 0 chars other than #, then a, digit and b. No checking for a whole word, nor actually matching words farther than at the beginning of a string.
You may use a regex that will match lines starting with # and match and capture the words you need in other contexts:
var s = "a1b a2b a3b\n#a4b a5b a6b\n a7b a8b a9b";
var res = [];
s.replace(/^[^\S\r\n]*#.*|\b(a\db)\b/gm, function($0,$1) {
if ($1) res.push($1);
});
console.log(res);
Pattern details:
^ - start of a line (as m multiline modifier makes ^ match the line start)
[^\S\r\n]* - 0+ horizontal whitespaces
#.* - a # and any 0+ chars up to the end of a line
| - or
\b - a leading word boundary
(a\db) - Group 1 capturing a, a digit, a b
\b - a trailing word boundary.
Inside the replace() method, a callback is used where the res array is populated with the contents of Group 1 only.
I would suggest to use 2 reg ex:
First Reg ex fetches the non-hashed lines:
^[^#][a\db\s]+
and then another reg ex for fetching individual words(from each line):
^a\db\s

Categories