-2

I need a regular expression to match two words, "abc4" and "abc20".

My solution is abc[4,20]. This does not work.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
ZZZ
  • 3,574
  • 10
  • 34
  • 37
  • 2
    Here is an answer that goes a little more in depth on this issue https://stackoverflow.com/questions/8020848/and-or-operator-in-regular-expression – ballmerspeak Feb 09 '18 at 16:25
  • 5
    Visual explaination on why yours did not work: https://regexper.com/#%2Fabc%5B4%2C20%5D%2F – epascarello Feb 09 '18 at 16:27
  • 1
    `[]` creates a character class that says *match any **character** in this class*. In your case, `[4,20]` will either match `4`, `,`, `2`, or `0`. You need to use the or `|` operator **outside** a character class as such: `(?:4|20)` – ctwheels Feb 09 '18 at 16:30
  • 1
    Check out this [fiddle](https://jsfiddle.net/jfd1yoL2/1/). If the question gets re-opened, I'll post it as an answer, but basically it's a function that will build a regex like: `/(part1[0])(part2[0]|part2[1])/g`. You simply provide it with the string you want to test against, and 2 arrays of parts to match, and it'll run. As you've simplified the question, this may be better suited to answer it. Note, that it probably wont play nice with regex special characters though, that may require a bit of editing – KyleFairns Feb 09 '18 at 17:35

1 Answers1

3

Please, try this one: /^abc(4|20)$/

let regExp = /^abc(4|20)$/

let strings = document.querySelectorAll(".example");

for (let string of strings) {
  if (string.innerHTML.match(regExp)) {
    string.style.background = "tomato";
  }
}
<div class="example">abc4</div>
<div class="example">4abc</div>
<div class="example">abc20</div>
<div class="example">bbb4</div>
<div class="example">abc20</div>
<div class="example">erw32</div>
<div class="example">abc4</div>
<div class="example">abc20</div>
<div class="example">turnip</div>

See online demo

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
mrzasa
  • 22,895
  • 11
  • 56
  • 94