0

I am trying to match the word ethane (preceded with nothing) while avoiding methane. I've tried this in an online regex tester: /(?<!m)ethane/i (which works), but I get an invalid regex expression error in JavaScript. What am I doing wrong?

Jake Smith
  • 2,332
  • 1
  • 30
  • 68
  • If you're using https://regex101.com/, make sure you select javascript, in flavor, instead of php. This might help: https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent – Darrennchan8 Jun 05 '17 at 02:58
  • 1
    JavaScript doesn't currently support look-behind patterns. Though, there's [an active proposal](https://github.com/tc39/proposal-regexp-lookbehind) for adding them (at the moment, the proposal is a "Candidate," [stage 3](https://github.com/tc39/proposals#active-proposals)). – Jonathan Lonowski Jun 05 '17 at 02:58
  • Neat, good to know. So if I'm using JavaScript, how would I match on "ethane" and not "methane"? – Jake Smith Jun 05 '17 at 03:00
  • You can try to use the "starts with" anchor. /^ethane/i . But this will force the string to start with 'ethane' (so for example it would match 'ethane', but not 'methane', and not 'word ethane') – syazdani Jun 05 '17 at 03:02
  • Do you want to match "ethane" as a separate word, or just those letters as long as they don't follow an "m"? Are "polyurethane" and/or "ethanediol" supposed to match? – nnnnnn Jun 05 '17 at 03:08
  • I want to match "Ethane", "ethane", " ethane", " ethane ", "ethane " (case-insensitive. I don't anticipate anything coming before "ethane" besides potentially some whitespace (tabula/ocr reasons). But methane usually shows up before ethane in the table I'm parsing. I've collected the methane row of the table, now I want to match on the ethane row of the table. Hope that helps! I really appreciate your help! – Jake Smith Jun 05 '17 at 03:18
  • 1
    When testing your regexps in a regexp tester, make sure to select the "JavaScript" flavor. –  Jun 05 '17 at 03:19

1 Answers1

2

You can use RegExp /\bethane\b/ to match "ethane" and not "methane"

var thanes = ["ethane", "methane"];
var re = /\bethane\b/;
thanes.forEach(word => console.log(re.test(word)));
  

See

guest271314
  • 1
  • 15
  • 104
  • 177