-3

I need Regex which matches when my string does not start with "MY" and "BY".

I have tried something like:

r = /^my&&^by/

but it doesn't work for me

eg

mycountry = false ; byyou = false ; xyz = true ;

Jason Aller
  • 3,475
  • 28
  • 40
  • 37
Ashutosh Jha
  • 13,573
  • 9
  • 48
  • 77
  • Give few test cases for your string ! – Tushar May 02 '18 at 12:26
  • 6
    use `string.startWith('my') || string.startsWith('by')` – diEcho May 02 '18 at 12:26
  • @Tushar updated – Ashutosh Jha May 02 '18 at 12:27
  • @pro.mean You definitely should write that as an answer. – Jeremy Thille May 02 '18 at 12:33
  • I'm genuinely curious about the answer to this as I'm not certain how to do a double-negative. While @pro.mean's response is valid javascript, it does not answer the question of how to do it using a regular expression. The vote to "close" means the voter did not actually read the question as the ask is very clear. – Jaime Torres May 02 '18 at 12:35
  • Possible duplicate of [RegExp matching string not starting with my](https://stackoverflow.com/questions/2116328/regexp-matching-string-not-starting-with-my) – revo May 02 '18 at 12:44

3 Answers3

4

You could test if the string does not start with by or my, case insensitive.

var r = /^(?!by|my)/i;

console.log(r.test('My try'));
console.log(r.test('Banana'));

without !

var r = /^([^bm][^y]|[bm][^y]|[^bm][y])/i;

console.log(r.test('My try'));
console.log(r.test('Banana'));
console.log(r.test('xyz'));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

if you are only concerned with only specific text at the start of the string than you can use latest js string method .startsWith

  let str = "mylove";

  if(str.startsWith('my') || str.startsWith('by')) {
    // handle this case
  }
diEcho
  • 52,196
  • 40
  • 166
  • 239
-1

Try This(Regex is NOT case sensitive):

  var r = /^([^bm][y])/i; //remove 'i' for case sensitive("by" or "my")

console.log('mycountry = '+r.test('mycountry'));
console.log('byyou= '+r.test('byyou'));
console.log('xyz= '+r.test('xyz'));

console.log('Mycountry = '+r.test('Mycountry '));
console.log('Byyou= '+r.test('Byyou'));

console.log('MYcountry = '+r.test('MYcountry '));
console.log('BYyou= '+r.test('BYyou'));
One Man Crew
  • 9,203
  • 2
  • 41
  • 51