最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex everything after x until space - Stack Overflow

programmeradmin1浏览0评论

Take xnum-539 classname random-word xnum-hello hi-239.

I need to pick out anything that is after xnum-, so in this case the 539, and hello.

I have tried multiple things and the best I've got to is either:

-(.*?)\s. But that includes the dash when I only want what's after the dash. (ex -539)

or

rnum-(.*?)\s which takes the whole thing.

For both solutions I don't want to have to manually slice. Apologies if this is a duplicate but I've tried to work with other answers and well I'm terrible at regex.

Thanks

Take xnum-539 classname random-word xnum-hello hi-239.

I need to pick out anything that is after xnum-, so in this case the 539, and hello.

I have tried multiple things and the best I've got to is either:

-(.*?)\s. But that includes the dash when I only want what's after the dash. (ex -539)

or

rnum-(.*?)\s which takes the whole thing.

For both solutions I don't want to have to manually slice. Apologies if this is a duplicate but I've tried to work with other answers and well I'm terrible at regex.

Thanks

Share Improve this question edited Jan 20, 2017 at 11:05 WillKre asked Jan 20, 2017 at 11:01 WillKreWillKre 6,1686 gold badges36 silver badges64 bronze badges 3
  • Is the example the extent of your data, or could there be an arbitrary number of xnum- entries? Never mind, Wiktor's answer has you covered :-) – Tim Biegeleisen Commented Jan 20, 2017 at 11:05
  • Actually, there is little one can do here, you just cannot use a plain String#match or RegExp#exec call since JS regex engine does not support a lookbehind. So, choose between slicing or running RegExp#exec inside a loop. – Wiktor Stribiżew Commented Jan 20, 2017 at 11:09
  • Unknown number of xnum- entries – WillKre Commented Jan 20, 2017 at 11:13
Add a ment  | 

1 Answer 1

Reset to default 5

Note your regex actually requires a whitespace (\s) at the end of the match, thus, stopping the regex engine to match your value at the end of the string.

You may get all matches with /xnum-(\S+)/g regex and access group 1:

var s = "xnum-539 classname random xnum-hello";
var res=[],m;
var re = /xnum-(\S+)/g;
while ((m=re.exec(s)) !== null) {
  res.push(m[1]);
}
console.log(res);

Pattern details:

  • xnum- - a sequence of literal chars xnum-
  • (\S+) - Capturing group with ID 1 matching one or more non-whitespace symbols.
发布评论

评论列表(0)

  1. 暂无评论