Regular expression not matching string - javascript

I'm trying to figure out the following regular expression:
/^[0-9]{2}-[0-9]{2,3}[a-zA-z]{0,1}/g
In my example.
The following should pass: 00-45, 00-333, 33-333a, 55-34a
The following should fail: 33-3333, 22-22dd, 22-2233
Here is my screenshot:
But the once that should fail arent failing. In my javascript code I just do a test:
var regExp = new RegExp(exp);
if(regExp.test(test1))
alert('pass');
else
alert('fail');
Is there a way for the regular expression to test the entire string? Example 33-3333 passes because of 33-333, but since there is another 3 I would like it to fail since the fourth 3 would be tested against the character rule?

You are missing end anchor $ in your input
A-z inside character class will match unwanted characters as well, you actually need A-Z
{0,1} can be shortened to ?
Try this regex:
/^[0-9]{2}-[0-9]{2,3}[a-zA-Z]?$/
RegEx Demo

Related

Javascript RegEx Templating Edge Case

I have a RegEx implemented with JavaScript that is close to doing what I want. However, I am having an issue figuring out the last piece which is causing an issue with an edge case. Here is the RegEx that I have so far:
/\$\{(.+?(}\(.+?\)|}))/g
The idea is that this RegEx would use a templating system to replace/inject variables in a string based on templated variables. Here is an example of the edge case issue:
"Here is a template string ${G:SomeVar:G${G:SomeVar:G} that value gets injected in."
The problem is the RegEx is matching this:
"${G:SomeVar:G${G:SomeVar:G}"
What I want it to match is this:
"${G:SomeVar:G}"
How would I get the RegEx to match the expected variable in this edge case?
You have an alternation in your pattern to either stop at } or also match a following (...) after it.
As the dot can match any character, you can use a negated character class to exclude matching { } ( )
If you want to match ${G:SomeVar:G} but also ${G:SomeVar:G}(test) you can add an optional non capture group after it.
For a match only, you can omit the capture groups.
\$\{[^{}]*}(?:\([^()]*\))?
See a regex101 demo.
If the format of the string with the : and the same character before and after it should be matched, you can use a capture group with a backreference:
\$\{([A-Z]):[^{}]*?:\1}(?:\([^()]*\))?
See a regex101 demo.
Instead of matching anything with (.+?), change it to not match another closing brace or dollar sign, [^{$].
\$\{([^{$]+?(}\(.+?\)|}))

Finding words between special characters using Unicode regex

I have a working regular expression which matches the words below.
Input:
(T1.Test)
(AT.Test)
Match:
T1.Test
AT.Test
But when I try replacing /w with unicode \p{L}, the regex does not work properly anymore.
Current expression: /(?:\w+\()+|\b(\p{L}+(?:\.\p{L}+)?)\b(?!')/gu
Input:
(T1.Test)
(AT.Test)
(ワーク.Test)
Match:
Test
Test
Test
How do I make my regex works properly now it has unicode flag?
My expected output should be:
T1.Test
AT.Test
ワーク.Test
First of all \p{L} does not catch numbers, so (T1.Test) will not be matched, while with \w would be.
Your regex is diveded in two big OR parts "1 | 2":
(?:\w+\()+ this non capturing group is matching anything of the shape anyAmmountOfLetter(. If this has success will totally ignore the rest of the regex, I don't know if it was intentional. This for example will trigger your regex: aaa(333.6780) with aaa( as full match, but 0 groups as you are not capturing it.
\b(\p{L}+(?:\.\p{L}+)?)\b(?!') this requires that you start your expression with a word boundary. But \b is valid in between two characters (Regex Tutorial) only if one is a word character an the other is not.
In your case, your starting round bracket will not be matched against the word boundary so (クーク.Test) will not work, but 3クーク.Test) will.
For fix that you can use only the second part (if the first is not really needed for checking something else of what you had shown in the question inputs):
// slight edited, can use digits: (3123.123) => 3123.123
input.match(/[\b]*\(([\d\p{L}]+(?:\.[\d\p{L}]+)?)\)[\b]*(?!')/gu)
// slight edited, must start with letter: (A1.Test) works, (1A.Test) doesn't
input.match(/[\b]*\((\p{L}[\d\p{L}]*(?:\.[\d\p{L}]+)?)\)[\b]*(?!')/gu)
Also the last part \b(?!') is optional for the input cases you gave, but I suppose it is usefull for other purposes.
If you want to keep the regex simple for those inputs, this would also work:
// can use digits: (3123.123) => 3123.123
input.match(/\(([\p{L}\d]+(?:\.[\p{L}\d]+))\)/gu)
// must start with letter: (A1.Test) works, (1A.Test) doesn't
input.match(/\((\p{L}[\p{L}\d]*(?:\.[\p{L}\d]+))\)/gu)

Error Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group

I'm checking if my string has special characters to replace but for the following string I'm having the following problem
String
(Lot P Verdes)
Function
function retira_acentos(palavra) {
com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
nova='';
for(i=0;i<palavra.length;i++) {
if (com_acento.search(palavra.substr(i,1))>=0) {
nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
}
else {
nova+=palavra.substr(i,1);
}
}
return nova.toUpperCase();
}
Error
line: if (com_acento.search(palavra.substr(i,1))>=0)
Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group
The problem you've stumbled across here is that String#search requires a regexp as input, you, however, seem to want to search for a string input, not a regexp. In that case, use String#indexOf instead.
Try changing these lines and see if it gives you the desired output:
if (com_acento.indexOf(palavra.substr(i,1))>=0) {
nova+=sem_acento.substr(com_acento.indexOf(palavra.substr(i,1)),1);
}
In regular expression, round parenthesis are used to define groups. In this case, the regex parser thinks that you opened a group but you forgot to close it.
You don't want to open a group, I guess. You just want to match the literal character.
To match literal characters, in javascript regex, you have two ways:
Escape the character with the backslace: \. Example: /\(/
Wrap your character in square brackets. Example: [(]
In your case, it would be preferrable to use the second approach, because it works with any character (even with the ones that don't need to be escaped) and works also with many characters.
So I advise you to change the parameter of search in this way:
search('['+palavra.substr(i,1)+']')

JS - Regex for one letter and 6 numbers

I have this regular expression to test if an input starts with the letter "a" and is followed by 6 numbers. On the online validator seems to work, but on JavaScript doesnt.
This is the code:
function checkBookingReference (ref) {
var regex = /(^a|A)([0-9]{6})/;
return regex.test(ref);
}
The function returns true if I enter more than six numbers, and it shouldn't. Any idea why?
That regex will return true if anywhere in the string there is a match. If you want to ensure the entire string matches it, then you'll want to use ^ to match the beginning and $ to match the end.
/^(a|A)([0-9]{6})$/
This is how I would do it:
return /^A[0-9]{6}$/i.test(ref);
Use the regex object to specify the regular expression and then test it. Try this
var regex = new RegExp("^a([0-9]{6})$","i");
return regex.test(ref);
You nee to move the carat ^ outside the parentheses and use a proper group around the letters, then loose the trailing dollar sign $. Try this:
var regex = /^[aA][0-9]{6}/;
The parenthesis inside meant "not". Outside it means "beginning of string". The dollar sign meant "end of string".

How to replace a substring with open parentheses (

I am a Regex newbie and trying to implement Regex to replace a matching pattern in a string only when it has a ( - open parentheses using Javascript. for example if I have a string
IN(INTERM_LEVEL_IN + (int)X_ID)
I would only like to highlight the first IN( in the string. Not the INTERM_LEVEL_IN (2 ins here) and the int.
What is the Regex to accomplish this?
To match the opening bracket you just need to escape it: IN\(.
For instance, running this in Firebug console:
enter code here"IN(INTERM_LEVEL_IN + (int)X_ID)".replace(/(IN()/, 'test');`
Will result in:
>>> "IN(INTERM_LEVEL_IN + (int)X_ID)".replace(/(IN\()/, 'test');
"testINTERM_LEVEL_IN + (int)X_ID)"
Parenthesis in regular expressions have a special meaning (sub-capture groups), so when you want them to be interpreted literally you have to escape them by with a \ before them. The regular expression IN\( would match the string IN(.
The following should only match IN( at the beginning of a line:
/^IN\(/
The following would match IN( that is not preceded by any alphanumeric character or underscore:
/[a-zA-Z0-9_]IN\(/
And finally, the following would match any instance of IN( no matter what precedes it:
/IN\(/
So, take your pick. If you're interested in learning more about regex, here's a good tutorial: http://www.regular-expressions.info/tutorial.html
You can use just regular old Javascript for regex, a simple IN\( would work for the example you gave (see here), but I suspect your situation is more complicated than that. In which case, you need to define exactly what you are trying to match and what you don't want to match.

Categories

Resources