0

I have the following Regular Expression: /i'm [a-zA-Z]|i am [a-zA-Z]*/i It works in terms of detecting when a phrase matches the regex, but I'm specifically trying to capture the [a-zA-Z] part. For example:

"I'm sam" // -> sam I am good at this // -> good

Tell me if this question needs any improvement. Thanks in advance! ^^

georg
  • 211,518
  • 52
  • 313
  • 390
Ben Rivers
  • 129
  • 10

2 Answers2

1

As of 2018, Javascript finally supports lookbehind assertions, so the following should work in latest browsers once it's implemented:

test = "i am sam";

console.log(test.match(/(?<=i'm |i am )[a-zA-Z]+/))

UPD: at the time of writing, only Chrome can do that, so this answer is going to be valid in a few months. In the meantime,

test = "i am sam";

console.log(test.match(/(?:i'm |i am )([a-zA-Z]+)/)[1])
georg
  • 211,518
  • 52
  • 313
  • 390
0

You could capture your words using a capturing group ([a-zA-Z]+):

I ?['a]m ([a-zA-Z]+)

This would match

I          # Match I
 ?         # Match an optional white space
['a]m      # Match ' or a followed by an m and a whitespace
(          # Capture in a group
 [a-zA-Z]+ # Match lower or uppercase character one or more times
)          # Close capturing group

Your words are in group 1.

var pattern = /I ?['a]m ([a-zA-Z]+)/;
var strings = [
  "I am good at this",
  "I'm sam"
];

for (var i = 0; i < strings.length; i++) {
  console.log(strings[i].match(pattern)[1]);
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70