Regular Expression Returns Undefined - javascript

I'm attempting one of the beginner coderByte challenges, Simple Symbols. Challenge summary below.
"Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter."
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
The first regular expression I'm testing, /^\w/gi, comes back undefined, and I can't figure out why?
https://regex101.com/ is a great tool I've used before, and my expression does identify f as the first character in the string, but when I test it in codepen, it comes back undefined in the console.

Code
See regex in use here
^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$
Alternatively, using the opposite logic (catching invalid strings instead of valid ones), you can use (?:^|[^+])[a-z]|[a-z](?:[^+]|$)
Usage
Please note the valid/invalid strings below have been created according to the OP's explanation of valid and invalid strings: That each letter must be surrounded by a + symbol. and that the plus sign + may be shared between characters such that +a+a+ is valid (specified in comments below the question).
var a = [
// valid
"++d+===+c++==+a++",
"+a+a+a+",
"+a++a+",
"+a+",
// invalid
"++d+===+c++==a",
"+=d+",
"+dd+",
"+d=+",
"+d+d",
"d+d+"
];
var r = /^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$/mi;
a.forEach(function(s){
console.log(r.test(s));
});
Explanation
^ Assert position at the start of the line
[+=\d]* Match any number of characters in the set (+, =, or digit)
\+ Match a literal plus sign +
(?:[a-z]\+[+=\d]*)+ Match one or more of the following
[a-z] Match a lowercase ASCII letter
\+ Match a literal plus sign +
[+=\d]* Match any number of characters in the set (+, =, or digit)
$ Assert position at the end of the line

It's returning undefined because your expression does not meet any of the criteria. Since you have no else {} defined, than nothing gets returned. Thus you get undefined. Try this:
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
} else {
return "catch all here";
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));

You can use a single regex and the string.test() method (which returns just true/false).
Below are 2 different ways (regex) to do it .
First requires a separate + between word chars. Example +a++b+ (true)
^
(?: [+=]* \+ \w \+ [+=]* )+
$
Second can take a common + between word chars. Example +a+b+ (true)
^
(?:
[+=]* \+ \w
(?= \+ )
)+
[+=]*
$
var patt1 = new RegExp("^(?:[+=]*\\+\\w\\+[+=]*)+$");
function SimpleSymbols_1(str){
return patt1.test(str);
}
var patt2 = new RegExp("^(?:[+=]*\\+\\w(?=\\+))+[+=]*$");
function SimpleSymbols_2(str){
return patt2.test(str);
}
console.log(SimpleSymbols_1('+d+=3=+s+'));
console.log(SimpleSymbols_1('f++d+'));
console.log(SimpleSymbols_1('+a+b+c+'));
console.log(SimpleSymbols_2('+a+b+c+'));
console.log(SimpleSymbols_2('+a+=+c+'));
console.log(SimpleSymbols_2('+a++c+'));

Thank you all for throwing some support/comments my way. Again, I am new to JavaScript and Regular Expressions are fairly foreign to me, though I am gaining some traction in understanding them. Here is the updated solution I posted. It's quite convoluted and perhaps a more inelegant and non-simple way to come to the right answer, but it worked.
function SimpleSymbols(str){
var RegExp = /\+[a-z]\+/gi;
var regexp1 = /^[a-z]/gi;
var regexp2 = /[a-z]$/g;
var regexp3 = /[a-z]\=/gi;
var regexp4 = /\=[a-z]/gi;
if(regexp1.test(str) === true){
return false
} else if(regexp2.test(str) === true){
return false
} else if(regexp3.test(str) === true){
return false
} else if(regexp4.test(str) === true){
return false
} else {
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
console.log(SimpleSymbols('+d===+a+'));
console.log(SimpleSymbols('+a='));
console.log(SimpleSymbols('2+a+a+'));
console.log(SimpleSymbols('==a+'));
I was sure there had to be a way to use only one regular expression, but again, I'm still very much a novice.
Thanks again everyone.

Related

Excluding matcher [duplicate]

After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]

How do I check for brackets in a specific place in the string?

I have this code and it needs to returns true or false based on the string you give it.
This is the only example on which it doesn't work. How can I check if brackets exist in a specific index of the string?
function telephoneCheck(str) {
var newStr = str.replace(/-/g,'').replace(/ /g,'').replace(/\(|\)/g,'');
var valid = true;
var re = /\([^()]*\)/g;
while (str.match(re))
str = str.replace(re, '');
if (str.match(/[()]/)){
valid = false;
}
if(newStr.length === 10 && valid === true && str.indexOf()){
return true;
}else if(newStr.length === 11 && str[0] != "-" && newStr[0] == 1 && valid === true){
return true;
}else{
return false;
}
}
telephoneCheck("(6505552368)");
Based on your code I think you might be looking for something like this:
'(6505552368)'.replace(/^\((\d+)\)$/, '$1');
The ^ and $ in the RegExp will match the start and the end of the string. The \d+ will match one or more numbers. The extra parentheses form a capture group that is then used in the replacement as $1.
You might be better off doing more work using RegExps rather than doing all that replacing but without knowing the exact requirements it's difficult to be more precise. I highly suggest learning more about RegExp syntax.
If you literally just want to know whether 'brackets exist in a specific index' then you can just use:
str.charAt(index) === '(';
To check if there are brackets at a specific index in the string:
/[()]/.test(str[index])
To check if there are any brackets in the string at all:
/[()]/.test(str)
If you want to test for a specific bracket type (e.g. opening but not closing) remove the other one (e.g. closing) from the regex.

JavaScript regex get number after string

After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]

Test String if each letter has '+' sign on both sides of it

this program is supposed to test str, and if every letter in str has a '+' sign on both sides of it then the function should return true. Otherwise, it should return false. I keep getting the error "SyntaxError: invalid quantifier".
function SimpleSymbols(str) {
var boolean = false;
for(var i=1;i<(str.length-1);i++){
if(/\w/.test(str.charAt(i))){
if(str.charAt(i-1).match('+') && str.charAt(i+1).match('+')){
boolean = true;
}else{
boolean = false;
}
}
}
str = boolean;
return str;
}
match is used for regular expressions, so it's trying to convert '+' to a regular expression, but it's failing because /+/ isn't a valid regular expression (it should be '\\+' or /\+/). But it's easier to just directly test each character, like this:
if(str.charAt(i-1) == '+' && str.charAt(i+1) == '+'){
Also note that /\w/ matches any 'word' character, which includes letters, numbers, and underscores. To mach just letter characters use should use /[a-z]/i (the i at the end makes it case-insensitive, so it will also match upper-case letters).
But it seems a lot simpler to invert the condition. Just test to see if the string contains any letter not surrounded by + signs or a letter at the beginning or end of the string, and return false if it does, like this:
function SimpleSymbols(str) {
return ! /(^|[^+])[a-z]|[a-z]([^+]|$)/i.test(str);
}
Much easier:
function SimpleSymbols(str) {
return !str.match(/[^+]\w/) && !str.match(/\w[^+]/);
}
The main problems with your function are:
You don't test if the first and last characters are letters. It should be safe to run your for loop from index 0 to < str.length because even though this will result in a str.charAt(-1) and str.charAt(str.length) when testing for '+' these just return "" rather than an error. Or of course you could continue with testing from the second character through to the second last in the loop and add an additional test for the first and last characters.
The .match() method does a regex match, so it tries to convert '+' to a regex and of course + has special meaning within a regex and doesn't match the literal. I'd suggest just using === '+' instead, though you could use .match(/\+/).
You are returning whatever value the boolean variable ends up with, which means your function is ignoring the tests on all but the second-last character in the string. You should return false immediately if you find a letter that doesn't have '+' around it.
Your question asked about "letters", but /\w/ doesn't test for a letter, it tests for letters or digits or underscores. If you actually want just letters use /[a-z]/i.
(Also there's no point assigning str = boolean, because JS function parameters are passed by value so this assignment won't affect anything outside the function.)
So:
function SimpleSymbols(str) {
for(var i=0;i<str.length;i++){
if(/[a-z]/i.test(str.charAt(i))){
if(str.charAt(i-1)!='+' || str.charAt(i+1) != '+'){
return false;
}
}
}
return true;
}

How to validate infix notation in javascript?

I have an infix expression: ((attribute1*attribute2)/attribute3+attribute4)
It may vary according to the user input. I want to check whether the expression is valid.
Valid example: ((attribute1*attribute2)/attribute3+attribute4)
Invalid example: (attrribute1*attribute2+*(attribute3)
The second one has no closing parenthesis; also the * operator is not needed. How can I perform this sort of validation in javascript?
Now this is my regex:
/ *\+? *\-? *[a-zA-Z0-9]+ *( *[\+\-\*\/\=\<\>\!\&\|\%] *\+? *\-? *[a-zA-Z0-9]+ *)*/
I need a regex for comparison operators like <= , >= , != , == etc. How can I implement this?
You could try something like this:
function validateInfix(infix) {
var balance = 0;
// remove white spaces to simplify regex
infix = infix.replace(/\s/g, '');
// if it has empty parenthesis then is not valid
if (/\(\)/.test(infix)) {
return false;
}
// valid values: integers and identifiers
var value = '(\\d+|[a-zA-Z_]\\w*)';
// the unary '+' and '-'
var unaryOper = '[\\+\\-]?';
// the arithmetic operators
var arithOper = '[\\+\\-\\*\\/]';
// the comparison operators
var compOper = '(\\<\\=?|\\>\\=?|\\=\\=|\\!\\=)';
// if it has more than one comparison operator then is not valid
if (infix.match(new RegExp(compOper, 'g')).length > 1) {
return false;
}
// the combined final regex: /[\+\-]?(\d+|[a-zA-Z_]\w*)(([\+\-\*\/]|(\<\=?|\>\=?|\=\=|\!\=))[\+\-]?(\d+|[a-zA-Z_]\w*))*/
var regex = new RegExp(unaryOper + value + '((' + arithOper + '|' + compOper + ')' + unaryOper + value + ')*');
// validate parenthesis balance
for (var i = 0; i < infix.length; i++) {
if (infix[i] == '(') {
balance++;
}
else if (infix[i] == ')') {
balance--;
}
if (balance < 0) {
return false;
}
}
if (balance > 0) {
return false;
}
// remove all the parenthesis
infix = infix.replace(/[\(\)]/g, '');
return regex.test(infix);
}
The idea is to check first the parenthesis balance, then remove them all given that we only want to validate and not evaluate, and then match the remaining expression to a regex (which may not be perfect, I'm not a regex expert). And... just in case: infix argument must be a string.
Edit
I noticed a couple of details and changed the code a bit:
Added the operators you needed the regex to match too.
Removed white spaces to get rid of regex junk.
Checked if the expression had empty parenthesis.
Checked if the expression had more than one comparison operators.
Changed this \+?\-? by this [\+\-]?.
Changed string match method by regex test method where possible.
Changed this [a-zA-Z0-9] by this (\d+|[a-zA-Z_]\w*) since the first one matches wrong identifiers like 53abc.
For better understanding and clarity, extracted pieces of regex into separate variables and built the final one from these.
Hope this is ok for you now :)

Categories