I have to match values like
€ 6.483,00
OR values like
18,50%
OR, again,
+65,86 %
in a Javascript function, which I drafted as:
function(s) {
return /^[0-9]?[0-9,\.]*$/.test(s);
}
but, obviously, it's not working... how should it be changed?
^(?:€|\+)?\s*\d+(?:\.?\d{3})*(?:,\d+)?\s*%?\s*$
See it here on Regexr
Start of the string, an optional € or +, then optional whitespace, Then there should be at list one digit, followed by an optional dot and three digits, then an optional fraction, optional whitespace, optional % more optional whitespace and then the end of the string,
var sample = [
"€ 6.483,00",
"18,50%",
"+65,86 %"
]
for(var i = 0; i < sample.length; i++) {
var input = sample[i];
var regex = /^(\u20ac ?)?\+?\d+(\.\d+)?(\,\d+)?( ?%)?$/
console.log(input + "\t" + regex.test(input));
}
If there are cases that do not/should not match then let me know.
Related
I have situation where I have to split the string in to 3 substrings.
Example
<=Mindate+30 >>> [<=,Mindate,+30]
<=Mindate >>> [<=,Mindate]
>=Maxdate-3 >>> [>=,Maxdate,-3]
==Date >>> [==,Date]
I have created a function that split current array in two
function splitString(str){
var a= /(>=|<=|=|<|>|\!=)|.+/g
return str.match(a);
}
splitString('<=Mindate+45');
Current output ['<=', 'Mindate+45']
Expected output ['<=', 'Mindate', '+45']
Can any one help me on this ?
You just needed to separate the textual part (\w+) from the number part ([-+]\d+):
function splitToThree(input) {
let regex = /(>=|<=|==|<|>|\!=)|\w+|[-+]\d+/g;
let ans = input.match(regex);
console.log(ans);
}
splitToThree("<=Mindate+30");
splitToThree("<=Mindate");
splitToThree(">=Maxdate-3");
splitToThree("==Date");
You can create a pattern that matches and captures all the comparison operators or matches a place before each of the +, /, * and - operators, and use the expression inside a String#split method:
a.split(/([<>!=]=|[=<>])|(?=[-+\/*])/).filter(Boolean)
See the JS demo:
var strs = ['<=Mindate+30', '<=Mindate','>=Maxdate-3','==Date','>=SomeFn-3.45'];
rx = /([<>!=]=|[=<>])|(?=[-+\/*])/;
for (var a of strs) {
var res = a.split(rx).filter(Boolean);
console.log(a, "=>", res);
}
Pattern details
([<>!=]=|[=<>]) - Group 1 (this value will be part of the resulting array): <, >, !, = followed with = or a =, < or > char
| - or
(?=[-+\/*]) - a location that is followed with -, +, / or *.
Note: .filter(Boolean) will remove empty items from the resulting array.
I want to check if the url is either in the pattern that:
end with digits:
www.example.com/projects/123
or possibly end with digits and /:
www.example.com/projects/123/
which I don't know if user is going to add in the / at the end of the url.
What I have currently is:
var lastPart = window.location.pathname.substr(window.location.pathname.lastIndexOf('/')+1);
lastPart.match(/\d$/);
this will return true if it end with digits. if I do:
lastPart.match(/\d\/$/);
this will return true if it end with digits with / at the end. However, we cannot be sure if the user will put in the / or not.
So, How can we write the regex which end with digits and optionally / at the end?
You may use a ? quantifier after /:
/\d+\/?$/
See the regex demo.
Details
\d+ - 1+ digits
\/? - 1 or 0 occurrences of /
$ - end of string.
JS demo:
var strs = ['www.example.com/projects/123', 'www.example.com/projects/123/', 'www.example.com/projects/abc'];
var rx = /\d+\/?$/;
for (var s of strs) {
console.log(s, '=>', rx.test(s));
}
You could do it like this and make the / optional ?:
\d+\/?$
Explanation
Match one or more digits \d+
Match an optional forward slash \/?
Assert the end of the string $
var strings = [
"www.example.com/projects/123",
"www.example.com/projects/123/"
];
for (var i = 0; i < strings.length; i++) {
console.log(/\d+\/?$/.test(strings[i]));
}
Try
/\d+(\/?)$/
Explanation
\d+ will match one or more digits
(\/?) will match zero or one /
$ asserts end of string
For example
window.location.pathname.match( /\d+(\/?)$/ )
Demo
var regex = /\d+(\/?)$/;
var str1 = "www.example.com/projects/123";
var str2 = "www.example.com/projects/123/";
var badStr ="www.example.com/projects/as";
console.log( !!str1.match( regex ) );
console.log( !!str2.match( regex ) );
console.log( !!badStr.match( regex ) );
var string = 'www.example.com/projects/123/';
console.log(string.match(/\d+(\/?)$/));
var string = 'www.example.com/projects/123';
console.log(string.match(/\d+(\/?)$/));
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);
I wanted to strictly match the strings like 45% or 2%.
It should not match if there are other strings added before or after the required string like abc34% or 34%cd212.
This will work for you:
const testData = (data) => /^(?:[1-9]\d?%|0%)$/.test(data)
const test = ["1.2%","120%","12%","2%", "ABc%", "1,3%", "23", "abc34%", "34%cd212", "00%", "0%"]
for(let x of test){
console.log(`${x} ${testData(x)}`)
}
^ begining of string
[1-9] number from 1 to 9
\d? optional 1 number
% % symbol
$ end of sting
|0% or 0%
You can use the following regex:
^\d+%$
^ Start of the string. This makes sure, that the string ABC45% is not allowed.
\d+ At least one number
$ End of the string. This makes sure, that the string 45%ABC is not allowed
Here is a live example:
var regex = /^\d+%$/;
var samples = [
"123%",
"ABC12%",
"ABC123%ABC",
"123%abc",
"abc"
];
for(var i=0; i<samples.length; i++) {
var sample = samples[i];
console.log(sample, !!sample.match(regex));
}
I am trying to use XRegExp to test if a string is a valid word according to these criteria:
The string begins with one or more Unicode letters, followed by
an apostrophe (') followed by one or more Unicode letters, repeated 0 or more times.
The string ends immediately after the matched pattern.
That is, it will match these terms
Hello can't Alah'u'u'v'oo O'reilly
but not these
eatin' 'sup 'til
I am trying this pattern,
^(\\p{L})+('(\\p{L})+)*$
but it won't match any words that contain apostrophes. What am I doing wrong?
EDIT: The code using the regex
var separateWords = function(text) {
var word = XRegExp("(\\p{L})+('(\\p{L})+)*$");
var splits = [];
for (var i = 0; i < text.length; i++) {
var item = text[i];
while (i + 1 < text.length && word.test(item + text[i + 1])) {
item += text[i + 1];
i++;
}
splits.push(item);
}
return splits;
};
I think you will need to omit the string start/end anchors to match single words:
"(\\p{L})+('(\\p{L})+)*"
Also I'm not sure what those capturing groups are needed for (that may depend on your application), but you could shorten them to
"\\p{L}+('\\p{L}+)*"
Try this regex:
^[^'](?:[\w']*[^'])?$
First it checks to ensure the first character is not an apostrophe. Then it either gets any number of word characters or apostrophes followed by anything other than an apostrophe, or it gets nothing (one-letter word).