0

Input

ABC - MMM

Expected output

MMM

Everything after - and a space

Tried this (-\s).+

But I dont get rid of - and space.

https://regex101.com/r/0W7lhD/2

Joe
  • 4,274
  • 32
  • 95
  • 175
  • 3
    No need for regex: `"ABC - MMM".split(" - ")[1]` – ctwheels Mar 19 '18 at 16:29
  • @ctwheels *Get everything after - and space, **regex** javascript* – Ele Mar 19 '18 at 16:29
  • 1
    @Ele yep, why use regex though when there's a string function to do just that? K.I.S.S. :) – ctwheels Mar 19 '18 at 16:30
  • You're capturing the dash and the space by putting them in the parentheses. Put the parentheses on the thing you want to capture. – SaganRitual Mar 19 '18 at 16:30
  • 3
    If you still want a regex after @ctwheels comment, capture the characters after the dash and space : `-\s(.+)` – Logar Mar 19 '18 at 16:31
  • @ctwheels the OP shows a sample, probably s/he needs to solve this using regex rather than split. – Ele Mar 19 '18 at 16:33
  • @Ele why though? If there's a better method. Why use a screwdriver to hit a nail into wood if you have a hammer? – ctwheels Mar 19 '18 at 16:33
  • @ctwheels Agree, however, you're assuming because the OP probably thought about the split and once again, s/he needs to solve this with regex. – Ele Mar 19 '18 at 16:38

3 Answers3

5

So there are multiple ways to go about this. The easiest and potentially best method is not to use regex at all.

Method 1 - split

Of course, you'd add a check to ensure that the element [1] exists, but this shows you the general idea of getting MMM.

console.log("ABC - MMM".split(" - ")[1])

Method 2 - regex group

This method groups everything you want into capture group 1.

console.log("ABC - MMM".match(/-\s(.+)/)[1])

Method 3 - regex lookbehind

This one was suggested by Andrew Bone in his answer here. While this works, it's currently only supported on Chrome 62+ (lookbehinds have little support in browsers at the moment). You can see the RegExp Lookbehind Assertions proposal here as part of EMCA TC39.

console.log("ABC - MMM".match(/(?<=-\s).+/)[0])
ctwheels
  • 21,901
  • 9
  • 42
  • 77
1

You want to use positive lookbehind which means look for things after, but not including, a pattern. The syntax is ?<=

(?<=-\s).+

Here is some further reading

Though this is the correct way to do this it's worth noting, as @ctwheels points out, support is currently very limited.

EDIT:

You can use split to turn the string into an array and then return the last string in the array.

This is a slightly long winded way to do it but I think it is more readable this way.

var string = "ADSD - ASDASD";
var regex = /(-\s)/;

function matchAfter(string, pattern) {
  var short = string.split(pattern);
  return short[short.length - 1];
}

console.log(matchAfter(string, regex));
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
0

You can capture the groups and get the last element from the array.

console.log(("ABC - MMM".match(/-\s+(.+)/) || []).pop());
Ele
  • 33,468
  • 7
  • 37
  • 75