-1

I am creating a binary calculator and I would like to create a regular expression to match the operands and a single operator. The regular expression that I've created works correctly for everything except the backslash \ character. Here is my regular expression:

re = /^([10]+)([\+\-\*\\]{1})([10]+)/;
re.test('11001+1000');
// true
re.test('11001-1000');
// true
re.test('11001*1000');
// true
re.test('11001\1000'); // I WOULD THINK THIS WOULD WORK
// false
re.test('11001\\1000'); // I WOULD THINK THIS WOULD FAIL
// true
re.test('11001++1000');
// false

Can anyone advise me on what I am doing wrong?

aquil.abdullah
  • 3,059
  • 3
  • 21
  • 40

3 Answers3

0

When you create string in JS with '\' - it is treated as escape character. Therefore '11001\\1000' will become '11001\1000', but creation of '11001\1000' will become "11001@0". You could try it:

let rr = '11001\1000';
console.log(rr);

Therefore '11001\\1000' is your case. And if you have string that already contains '11001\1000' - it will work.

Alex Vovchuk
  • 2,828
  • 4
  • 19
  • 40
0

re.test('11001\1000');

Javascript does not see that string as "11001\1000" like you do. It sees it as the sequence of characters "1", "1", "0", "0", "1", "\100", "0". Whenever a backslash appears in a javascript string, it is interpreted as an escape symbol combined with one or more following characters. If the following character is a digit, it reads in up to 3 characters, and treats them as a character code in octal. The character code in octal 100 converts to the @ symbol, so the end result of that string is "11001@0".

However, if the character immediately following the backslash is another backslash, it realizes that you mean a literal backslash, and so you get the following:

11001\\1000
becomes
1 1 0 0 1 \\ 1 0 0 0
becomes
11001\1000

which is what you want.

David Sampson
  • 727
  • 3
  • 15
0

Division sign is / not \

re = /^[10]+[-+*\/][10]+/;
console.log(re.test('11001+1000'));
console.log(re.test('11001-1000'));
console.log(re.test('11001*1000'));
console.log(re.test('11001/1000')); 
console.log(re.test('11001\\1000'));
console.log(re.test('11001++1000'));
Toto
  • 89,455
  • 62
  • 89
  • 125