I'm really trying to understand RegEx and I feel like this issue should be easy and straightforward, but for some reason I'm really struggling to get exactly what I need. I've looked through at least 20 articles here and none of them are getting me there.
What I need is to capture all words after a lookbehind so I can count them. Here's what I've got so far:
RegEx: /(?<=\> )(\w*)/gi
String: "Mon Jan 11 11:00 <ralph> Hello all!!"
Capture all words after "> "
, so in the above I only want the capture group to individually capture "Hello" and "all", so I can count the group and get the number words after the username, "<ralph>" in this example.
The above RegEx is just what I'm currently working with and it of course is only capturing the first word. I've also tried putting * and after the capture group, but that nullifies the capture group for some reason.
I've also tried (?<=\> )((\w*)(?:\W ))*
, and while this does match everything after the lookbehind, it only captures "all!!" and "all" in the 2 different captures. I'm not sure why "!!" is returning in any capture as I have it to match only with (?:).
EDIT: Resolved and I've realized I misunderstood capture groups, hehe. The solution I went with is /(?<=> .*)\w /g as it's a bit more fitting to my needs than MikeM's solution below, but they both achieve the same thing. Mike's is a bit more robust and captures conditions I don't need to be concerned with in this instance. If Wiktor doesn't post as an answer, I'll accept Mike's shortly.
CodePudding user response:
(?<=\> )(. )
works fine for me it captures Hello all!!
from Mon Jan 11 11:00 <ralph> Hello all!!
Is it what you need?
CodePudding user response:
Is there a regular pattern after the >
or it's random?
Anyway, this (?<=\> )(.*)
matches your example.
CodePudding user response:
For example
const str = "Mon Jan 11 11:00 <ralph> Hello all. How are you?";
console.log( str.match(/(?<=\> (?:\w \W )*)\w /g) );
I'm not sure why "!!" is returning in any capture as I have it to match only with (?:).
Yes, but it is also captured by the first capture group. For example, if "x"
is matched by ((?:x))
, then the first capture group will contain "x"
even though it is also inside the second group which is non-capturing.