Js Regex only allowed characters one occurence - javascript

Trying the regex very hard but could not get the desired result.
Must begin with numbers and maximum of 4
followed by only one allowed alphabet
Please have a look at below code.
var strings = [
'1h', //should match
'13s', //should match
'30m', //should match
'42hr', //should not match
'8 hours ', //should not match
'765765', //should not match
'5sec', //should not match
'23445345345s', //should not match
'335m' //should match
];
for (var i = 0; i < strings.length; i++)
{
var match = strings[i].match(/\d{4}[h|m|s]{1}/g);
console.log(strings[i], (match ? "Match" : "Not match"));
}

You regex should be:
/^\d{1,4}[hms]$/gm
First, you require 4 digits with d{4}
Change it to d{1,4} to be one to four digits
Then add a $ to indicate the end of the string, so it doesn't allow more characters after the letter
Check out Regex101, Really useful for testing and understanding regex

I've added a ^ to match from start
strings.filter(x => x.match(/^\d{1,4}[hms](?!\w)/g) )

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

Is it possible to have one regex that solves this task?

string = '1,23'
When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.
Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.
Also, we can't reverse the order of the string to solve this task.
I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.
You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with
/^(?:[^,]*,)?(\d)/
See the regex demo.
Details
^ - start of string
(?:[^,]*,)? - an optional sequence of
[^,]* - 0 any chars other than a comma
, - a comma
(\d) - Capturing group 1: any digit
See the JavaScript demo:
const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
const result = (s.match(rx) || ['',''])[1];
// Or, const result = s.match(rx)?.[1] || "";
console.log(s, '=>', result);
}

regular expression replacement in JavaScript with some part remaining intact

I need to parse a string that comes like this:
-38419-indices-foo-7119-attributes-10073-bar
Where there are numbers followed by one or more words all joined by dashes. I need to get this:
[
0 => '38419-indices-foo',
1 => '7119-attributes',
2 => '10073-bar',
]
I had thought of attempting to replace only the dash before a number with a : and then using .split(':') - how would I do this? I don't want to replace the other dashes.
Imo, the pattern is straight-forward:
\d+\D+
To even get rid of the trailing -, you could go for
(\d+\D+)(?:-|$)
Or
\d+(?:(?!-\d|$).)+
You can see it here:
var myString = "-38419-indices-foo-7119-attributes-10073-bar";
var myRegexp = /(\d+\D+)(?:-|$)/g;
var result = [];
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
result.push(match[1]);
match = myRegexp.exec(myString);
}
console.log(result);
// alternative 2
let alternative_results = myString.match(/\d+(?:(?!-\d|$).)+/g);
console.log(alternative_results);
Or a demo on regex101.com.
Logic
lazy matching using quantifier .*?
Regex
.*?((\d+)\D*)(?!-)
https://regex101.com/r/WeTzF0/1
Test string
-38419-indices-foo-7119-attributes-10073-bar-333333-dfdfdfdf-dfdfdfdf-dfdfdfdfdfdf-123232323-dfsdfsfsdfdf
Matches
Further steps
You need to split from the matches and insert into your desired array.

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

Returning matched lookahead groups

Good day,
I am trying to return groups of 3 digits of a given string where digits are "consumed" twice in JavaScript:
From a string "123 456" I would like exec to return ["1", "12"] for the first match, ["2", "23"] and so on.
I tried using a lookahead like this:
let exp = /(\d(?=\d\d))/g;
let match;
while(match = exp.exec("1234 454")) {
console.log(match);
}
This, will however still only each digit which precedes two digits.
Does someone have a solution? I have searched but am not exactly sure what to search for so I might have missed something.
Thank you in advance!
You need to capture inside a positive lookahead here:
let exp = /(?=((\d)\d))/g;
let match;
while(match = exp.exec("1234 454")) {
if (match.index === exp.lastIndex) { // \
exp.lastIndex++; // - Prevent infinite loop
} // /
console.log([match[1], match[2]]); // Print the output
}
The (?=((\d)\d)) pattern matches a location followed with 2 digits (captured into Group 1) the first being captured into Group 2.

Categories