I have a quick regex verification for an input string.
This is an example string format I am trying to achieve: ABC=10:1;
What I currently have: var reg = new RegExp('(([AWT]\\w\\S=)?(\\d{0,9}:)?(\\d{0,9});)');
With the above regex I am able to get the string, however all these strings are also getting accepted...
ABC=
ABC=a:a;
ABC=#:#;
What I need: Three letter string = Any number(0-9) : Any number(0-9) ;
Unacceptable criteria (like the examples above)
Anything non-numerical after the equals sign and after the colon should be considered unacceptable.
Anything after the Semi-colon.
Anything before the Three letter string.
Any help would be appreciated!
Thank you.
Updates
According to the answers below, "^[a-zA-Z]{3}=\d+:\d+;$" works perfectly fine, however when I test it with my code, it's invalid.
Here is the code:
var reg = new RegExp("^[a-zA-Z]{3}=\d+:\d+;$");
var x = $('td').find('input')[7].value;
console.log(x); // AWT=10:15;
if (!x.match(reg)) {
return [false, "Stop"];
console.log("Invalid");
} else {
return [true, 'Success'];
console.log("Valid");
}
The above code always spits out Invalid even though I tested the regex.
I don't know whats wrong here.
Looks like your regexp could be simplified to this:
"^[a-zA-Z]{3}=\d+:\d+;$"
Where:
^ and $ - the beginning and the end of the line
[a-zA-Z] - any characters from the range (latin characters in this case)
{3} - exact number of the previous symbols (3 any latin characters in this case)
\d - any digit
+ - repeat last symbol one or more times
symbols =:; don't have to be escaped in this case
UPD:
If you need only one digit before the colon and one after the colon, then you shouldn't use + signs, just like in Cary Swoveland comment. But, according the example, there could be arbitrary length numbers here
Related
I am trying to find a way to extract the numbers that occur after abc/ immediately succeeding the / and before any further letters, numbers or punctuation.
E.g:
abc/134567/something should return 1234567
abc/1234567?foo=bar should still only return 1234567
blah/1234/abc/678 should only return 678 as I'm looking only for the number that succeeds abc/
I'm aware there are two options: regex or substring match.
In order to perform the substring match I need the index point but I'm dubious about merely doing an indexOf("abc/") as it only returns the index of the first letter - a - which could be present elsewhere in the string.
With regex I have struggled as I find that searching for a mixture of the letters and the slashes seems to cause it to return null.
So what's the best way?
You can use this regexpression :
var rgx = new RegExp("abc\/([0-9]+)","gi");
Then :
var m = rgx.exec("abc/1234567?foo=bar");
console.log(m[0]);
edited after comments
You could use a regular expression and seach for abc/ and following digits.
var array = ['abc/134567/something', 'abc/1234567?foo=bar', 'blah/1234/abc/678'];
console.log(array.map(s => s.match(/abc\/(\d+)/)[1]));
We accept string that has abc/, after it an integer number, that is taken as a matched group and either the end of string or some non-digit symbol after it.
abc\/(\d+)(?:$|\D)
test
You'll use in Javascript for matched group extraction:
var myRegexp = /abc\/(\d+)(?:$|\D)/g;
var match = myRegexp.exec(inputString);
var result=match[1]; // the number after abc/
In another regex engine than that of JavaScript, lookahead and lookbehind could be used. But in JS lookbehinds are forbidden. :-(. So we have to use this, a bit more complicated, way.
Are you after something like this:
^(.*\/)(\d+)(.*)
Where the second group will give you the digits after the slash.
Look at the regex here
I need two regular expression.
1) Any characters followed by a comma followed by any characters followed by a comma followed by any characters.
Currently I have:
/(.*,.*,.*)/
2) Any characters followed by a comma followed by any characters so long as they are not a comma.
Currently I have:
/(.*,.*[^,]+.*)/
Any help would be much appreciated. Thanks in advance!
For your first Regex you could really just use Javascript built in string.split(","); Which would return an array of strings. From there run a check for array.length >= 3 and you'll know the string matched you pattern. That being said f there are commas in the characters after that second required comma you could have issues depending on what you are expecting.
The second Regex could be verified using string.split(",") as well. Your second check would just be array.length === 2
The full code would be something like this
function verify(str) {
var arr = str.split(",");
if (arr.length < 2)
return "Invalid string provided";
if (arr.length === 2)
return arr[0] + arr[1];
return join(arr);
}
verify("some,crazy,comma delimited voodoo");
For your first regular expression, /(.*,.*,.*)/, you have what you're looking for. Note that "any character" includes commas, so really this only guarantees that there will be at least 2 commas.
For the second, /(.*,.*[^,]+.*)/, that's not quite right. "Any characters followed by a comma followed by any characters so long as they are not a comma" would be /(.*,[^,]*)/. However again, consider that "any characters" includes commas, so it is somewhat meaningless.
Perhaps you mean something more like /([^,]*,[^,]*)/? This is any text with precisely one comma. You can repeat the pattern by adding a second ,[^,]* as you wish, for example /([^,]*,[^,]*,[^,]*)/ is for precisely two commas.
If you wish to match any number of items separated by commas, try /([^,]+,?)/g to match each individual list item.
If you also require that there is text between commas, use + instead of *.
I don't know the utility of your regular expressions but in the linux grep command this will work:
grep '?,?,?'
grep '?,*[^,]'
I'm trying to write code that removes all after the first block of numbers and text.Do you have any idea how to do this.
string = '009EPMT18$MBS'
the expected result
string = '009EPMT'
You'll need regex to do that. It's a string analysis syntax common in many languages. There are many regular expressions which would do what you want, here's one:
var myRegex = /^[0-9]+[a-zA-Z]+/;
^ means that the search must begin at the start of the string.
[0-9] means that right after the beginning, there must be characters in the 0 to 9 range.
+ means there must be one or more of the previous condition, meaning there must be one or more digits.
[a-zA-Z] means there must be any character in the range a to z or A to Z. This won't include accented characters and letters from other alphabets though.
Calling .exec(string) on a regex returns an array of found strings in the passed string.
You were on the right track, the letters were just missing from your pattern:
var s = '009EPMT18$MBS';
var result;
var m = s.match(/^\d+[A-Z]+/); // first numbers and uppercase text
if (m) result = m[0]; // result = "009EPMT"
Regex explanation: beginning of string ^ followed by 1 or more digits \d+ followed by 1 or more letters from A to Z [A-Z]+. Note that lowercase characters will not match.
We had a developer here who had added following line of code to a web application:
var amount = newValue.replace(/[^\d.-]/g, '');
The particular line deals with amount values that a user may enter into a field.
I know the following about the regular expression:
that it replaces the matches with empty strings (i.e. removes them)
that /g is a flag that means to match all occurrences inside "newValue"
that the brackets [] denote a special group
that ^ means beginning of the line
that d means digits
Unfortunately I do not know enough to determine what kind of strings this should match. I checked with some web-based regex testers if it matches e.g. strings like 98.- and other alternatives with numbers but so far no luck.
My problem is that it seems to make IE very slow so I need to replace it with something else.
Any help on this would be appreciated.
Edit:
Thanks to all who replied. I tried not just Google but sites like myregextester.com, regular-expressions.info, phpliveregex.com, and others. My problem was misunderstanding the meaning of ^ and expecting that this required a numeric string like 44.99.
Inside the group, when the ^ is the first character, it works as a negation of the character matches. In other words, it's saying match any character that are not the ones in the group.
So this will mean "match anything that is not a digit, a period, or a hyphen".
The ^ character is a negation character.
var newValue = " x44x.-x ";
var amount = newValue.replace(/[^\d.-]/g, '');
console.log(amount);
will print
44.-
I suspect the developer maybe just wanted to remove trailing whitespaces? I would rather try to parse the string for numbers and remove anything else.
I am learning javascript and Regex and trying to validate a input if the first letter in the string is in uppercase.
my current Regex is : var patt1=/[A-Z]{4}$/;
but this is validating the string if all the four letters are in uppercase not the first letter only.
Any idea how to make it work.
Note : I am also checking the input should be 4 letter long.
Provided that by "uppercase" you mean a letter in A-Z, then you may use
var isFirstLetterUppercase = /^[A-Z]/.test(yourString);
The idea here (and in similar cases) is to use ^ which matches the start of the string.
If you also want to check the length of the string, you may use :
var isOK = /^[A-Z].{3}$/.test(yourString);
Here, .{3} means 3 characters and $ is the end of the string.
The problem with using an A-Z test in a regular expression is that A-Z are not the only uppercase letters.
Consider the city of Überlingen in Germany. The first letter certainly is uppercase, but it is not in the range A to Z. Try it in the JavaScript console:
/^[A-Z]/.test('Überlingen'); // logs false - oops!
Now here is where it gets a bit tricky. What exactly does it mean for a letter to be uppercase? In English it's simple: A-Z vs. a-z. In German, Ü (for example) is uppercase and ü is lowercase. For languages like these that have both uppercase and lowercase characters, you can test if a character is uppercase by converting it to lowercase with the .toLowerCase() method and comparing that with the original. If they are different, the original was uppercase. If they are the same, the original was either a lowercase character or a character that doesn't have uppercase and lowercase versions (e.g. a number or punctuation mark).
// 'char' is a string containing a single character
function isUpperCase( char ) {
return char !== char.toLowerCase();
}
Now you can test if the first character of a string is uppercase by extracting that character with .charAt() and calling isUpperCase():
function beginsWithUpperCase( string ) {
return isUpperCase( string.charAt(0) );
}
This works correctly for the German city:
beginsWithUpperCase( 'Überlingen' ); // logs `true`.
And now, since we're not using a regular expression at all, if you want to check the string length, merely use the .length property:
function fourCharactersWithFirstUpperCase( string ) {
return string.length === 4 && beginsWithUpperCase( string );
}
fourCharactersWithFirstUpperCase( 'über' ); // logs false
fourCharactersWithFirstUpperCase( 'Über' ); // logs true
fourCharactersWithFirstUpperCase( 'Überlingen' ); // logs false
So we're in good shape for languages that have both uppercase and lowercase versions of the same character. But what about languages that don't have uppercase vs. lowercase characters? Then this code would return false for any string.
I don't have a good solution for that off the top of my head; you'd have to think about how you want to handle that case.
BTW if you really want to try this with a regular expression, there's a possible approach in this answer. Instead of just testing for A-Z, you could list all of the uppercase letters in the languages you may have to deal with. Adapting the regex from that answer, it might look like this:
function beginsWithUpperCase( string ) {
return /^[A-ZÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]/.test( string );
}
Of course that raises the question of whether we've accurately listed all of the uppercase characters for every language!