I need a regex which satisfies the following conditions.
1. Total length of string 300 characters.
2. Should start with &,-,/,# only followed by 3 or 4 alphanumeric characters
3. This above pattern can be in continuous string upto 300 characters
String example - &ACK2-ASD3#RERT...
I have tried repeating the group but unsuccessful.
(^[&//-#][A-Za-z0-9]{3,4})+
That is not working ..just matches the first set
You may validate the string first using /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/ regex and checking the string length (using s.length <= 300) and then return all matches with a part of the validation regex:
var s = "&ACK2-ASD3#RERT";
var val_rx = /^(?:[&\/#-][A-Za-z0-9]{3,4})+$/;
if (val_rx.test(s) && s.length <= 300) {
console.log(s.match(/[&\/#-][A-Za-z0-9]{3,4}/g));
}
Regex details
^ - start of string
(?:[&\/#-][A-Za-z0-9]{3,4})+ - 1 or more occurrences of:
[&\/#-] - &, /, # or -
[A-Za-z0-9]{3,4} - three or four alphanumeric chars
$ - end of string.
See the regex demo.
Note the absence of g modifier with the validation regex used with RegExp#test and it must be present in the extraction regex (as we need to check the string only once, but extract multiple occurrences).
You're close. Add the lookahead: (?=.{0,300}$) to the start to make it satisfy the length requirement and do it with pure RegExp:
/(?=.{0,300}$)^([&\-#][A-Za-z0-9]{3,4})+$/.test("&ACK2-ASD3#RERT")
You can try the following regex.
const regex = /^([&\/\-#][A-Za-z0-9]{3,4}){0,300}$/g;
const str = `&ACK2-ASD3#RERT`;
if (regex.test(str)) {
console.log("Match");
}
Related
Input string is "F000668A - EED14F50 - 000EED1KFF0000000F03".
I want to print/save 4 characters after EED1. The number of EED1 can 1 or more.
In the above example, the expected result is => 4F50,KFF0.
My code:
var input = "F000668A - EED14F50 - 000EED1kFF0000000F03"
const string = input.toLowerCase().replace(/\s/g, '').replace(/(\r\n|\n|\r)/gm, ""); //Lowercase it, delete spaces and linebreaks.
string.match(/eed1/g).forEach((element) => {
console.log(element)
});
Result:
eed1
eed1
But when I try to print further characters then the script print only 1 item.
string.match(/eed1(.*)/g)
Result:
eed14f50-000eed1kff0000000f03
How can I get the requested info with regex? (or an other way)
Thank you in advance.
You can use
const input = "F000668A - EED14F50 - 000EED1kFF0000000F03";
const matches = input.replace(/\s/g, '').matchAll(/eed1([a-z0-9]{4})/ig);
console.log(Array.from(matches, m => m[1]));
Note:
You do not need to replace line breaks separately from other whitespaces, \s matches \n, \r, and the rest of vertical whitesapce
There is no need to lowercase the input, you can use /i flag to match in a case insensitive way
/eed1([a-z0-9]{4})/ig will match all occurrences of eed1 (case insensitively) and then capture four letters/digits, and matchAll will ensure the access to all the capturing group values (match() discarded them all as the regex was built with the g flag).
See the regex demo.
examples where the regex should return true: 1&&2, 1||2, 1&&2||3, 1
examples where the regex should return false: 1||, 1&&, &&2
My regex is:
[0-9]+([\\|\\|\\&&][0-9])*
but it returns true if the input is 1&&&2.
Where is my mistake?
Note that [\|\|\&&] matches a single | or & char, not || or && sequences of chars. Also, the [0-9] without a quantifier matches only one digit. Without anchors, you may match a string partially inside a longer string.
You may use
^[0-9]+(?:(?:\|\||&&)[0-9]+)*$
Actually, to match anywhere inside a string, keep on using the pattern without anchors:
[0-9]+(?:(?:\|\||&&)[0-9]+)*
See the regex demo
Details
^ - start of string
[0-9]+ - 1+ digits
(?:(?:\|\||&&)[0-9])* - 0 or more repetitions of
(?:\|\||&&) - || or && sequence of characters
[0-9]+ - 1+ digits
$ - end of string.
JS demo:
const reg = /^[0-9]+(?:(?:\|\||&&)[0-9]+)*$/;
console.log( reg.test('1||2') ); // => true
I am new to regular expression, In my project i am allowing user to put amount in shorthand as well as full digit, i have used material UI TextField for input.
Examples are:
400k - shorthand,
400.2k - shorthand,
4m - shorthand,
500. - should work
500000 - full amount
some pattern user should not be allowed to enter example are:
4.2.k,
.3k,
4...k
300.k
I have written regex which is below but it does allows to enter dot after number.
textValue.match(/^[0-9]*(\.[0-9]{0,2})*([0-9km]{1})$/) && textValue.match(/^[\d]+/)
above code first regex validates the pattern and second regex forces user to put Number because amount cannot start with string, i have wrote two separate regex as i don't understand how to put them in one regex and those regex doesn't accepts dot after number. Please can anyone give a perfect Regex to validate the above pattern in one single regular expression??
Thanks in advance
With alternation (never really the prettiest) it could be done like:
^\d+([km]|\.|\.\d+[km])?$
See the Online Demo
^ - Start string ancor.
d+ - One or more digits.
( - Opening capturing group (you could use non-capturing).
[km] - A single character "k" or "m".
| - Alternation (OR).
\.? - A literal dot.
| - Alternation (OR).
\.\d+[km] - A literal dot followed by at least one digit and a character "k" or "m".
)? - Close capturing group and make it optional
$ - Start string ancor.
About the pattern you tried
Note that you don't need {1}. The character class [0-9km] matches 1 of a char k or m or a digit 0-9. This way the possible digits to match could be 0-3 instead of 0-2.
Using the quantifier * for the group makes it possbile to also match 400.25.22.22.22k
You could use this pattern to validate the examples. The [0-9]+ at the beginning of the pattern makes sure that there has to be at least a single digit present.
If you want to allow 500. you could use:
^[0-9]+(?:(?:\.[0-9]{1,2})?[km]?|\.)$
Explanation
^ Start of string
[0-9]+ Match 1+ digits
(?: Non capture group
(?:\.[0-9]{1,2})? Match an optional decimal part with 2 digits
[km]? Match optional k or m
| Or
\. Match a single dot
)$ End of string
Regex demo
let pattern = /^[0-9]+(?:(?:\.[0-9]{1,2})?[km]?|\.)$/;
[
"400k",
"400.2k",
"4m",
"500000",
"500.",
"300.k",
"4.2.k",
".3k",
"4...k",
].forEach(s => console.log(s + " --> " + pattern.test(s)));
Another option is to only match the dot when not directly followed by k or m
^[0-9]+(?:\.(?![km]))?\d*[km]?$
Regex
You can try:
^\d+\.?(?:\d+)?[KkMm]?(?<!\.[KkMm])$
Explanation of the above regex:
^, $ - Matches start and end of the line respectively.
\d+ - Matches digits 1 or more times.
\.? - Represents 0 or 1 occurrence of ..
[KkMm]? - Matches optional characters from the mentioned character class.
(?<!\.[KkMm]) - Represents a negative look-behind not matching a a character after ..
You can find the demo of the above regex in here.
const regex = /^\d+\.?(?:\d+)?[KkMm]?(?<!\.[KkMm])$/gm;
const str = `400K
4.2.K
4.3K
3.2M
300000
4....K
4K
500.
300.K`;
let m;
while ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`${match}`);
});
}
2nd efficient solution using alternation:
You can probably try this regex for more efficient implementation
^\d+(?:\.$|\.\d+)?[KkMm]?$
Explanation of the above regex:
^, $ - Matches start and end of the line respectively.
\d+ - Matches digits 1 or more times.
(?:\.$|\.\d+)? - Represents a non-capturing group; matching either numbers followed by only . or decimal numbers.
[KkMm]? - Matches one of the mentioned characters zero or 1 time.
You can find the demo of the above regex in here.
const regex = /^\d+(?:\.$|\.\d+)?[KkMm]?$/gm;
const str = `400K
4.2.K
4.3K
3.2M
300000
4....K
4K
500.
300.K`;
let m;
while ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`${match}`);
});
}
I trying to validate 5 comma separated email id in one regular expression.
I currntly using below regex
^([\w+-.%]+#[\w-.]+\.[A-Za-z]{2,4},?)+$
This is valid for one email id.
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
First of all, fix the pattern: - in between two chars inside a character class forms a range. So, the email part of your regex should be [-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4} (note the position of - in the first character class, in the second, it is OK to put it between a shorthand character class \w and the next char).
Next, to match 1 to 5 comma-separated emails, you need to match the first one, and then match 0 to 4 emails. And add anchors around the pattern to make sure the pattern matches the whole string:
^[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}(?:,[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}){0,4}$
Basically, ^<EMAIL>(?:,<EMAIL>){0,4}$:
^ - start of string
<EMAIL> - an email pattern of yours
(?: - start of a non-capturing group acting as a container for a sequence of patterns:
, - a comma
<EMAIL> - an email pattern of yours
){0,4} - zero to four occurrences of these sequences above
$ - end of string.
Another idea is to split with , and then validate:
var s = "abc#gg.com,abc2#gg.com,abc3#gg.com,abc4#gg.com,abc5#gg.com";
var re = /^[-\w+.%]+#[\w-.]+\.[A-Za-z]{2,4}$/;
var items = s.split(",");
if (items.length <= 5 && items.filter(function(x) { return re.test(x); }).length === items.length ) {
console.log("VALID => ", items);
} else {
console.log("INVALID!");
}
Below regex for javaScript you can use for multiple comma separated email id, hope this work for you
/^(\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}\s*?,?\s*?)+$/
I need a regex for validating a string / decimal in JavaScript.
Which can be max 9 elements long with 2 decimals
Simply
123 - valid
123456789 - valid
1234567896 - invalid ( max 10 chars )
123. - invalid
123.2 - valid
123.32 valid
123.324 invalid ( 3 decimal points )
So I wrote a regexp like this
/^([0-9]{1,9})+[.]+([0-9]{0,2})$/
Can any one plz fine tune this regex
You can use regex ^(?=.{0,10}$)\d{0,9}(\.\d{1,2})?$
$('input').on('input', function() {
$(this).css('color', this.value.match(/^(?=.{0,10}$)\d{0,9}(\.\d{1,2})?$/) ? 'green' : 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type=text/>
Regex explanation here
Give the following a try:
^\d{1,9}(\.\d{1,2})?$
Something like this?
/^[0-9]{1,9}(\.[0-9]{0,2})?$/
You may use a negative lookahead at the beginning to apply a length restriction to the whole match:
^(?!\S{10})\d+(?:\.\d{1,2})?$
See regex demo
^ - start of string
(?!\S{10}) - no more than 9 non-whitespace characters from the beginning to end condition
\d+ - 1 or more digits
(?:\.\d{1,2})? - 1 or zero groups of . + 1 or w2 digits
$ - end of string
However, you might as well just match the float/integer numbers with ^\d+(?:\.\d{1,2})?$ and then check the length of the matched text to decide whether it is valid or not.
Note that in case you have to omit leading zeros, you need to get rid of them first:
s = s.replace(/^0+/, '');
And then use the regex above.