开发者

Regex equivalent to str.substr(0, str.indexOf('foo'))

开发者 https://www.devze.com 2023-03-06 23:32 出处:网络
Given this string: var str = \'A1=B2;C3,D0*E9+F6-\'; I would like to retrieve the substring that goes from the beginning of the string up to \'D0*\' (excluding), in this case:

Given this string:

var str = 'A1=B2;C3,D0*E9+F6-';

I would like to retrieve the substring that goes from the beginning of the string up to 'D0*' (excluding), in this case:

'A1=B2;C3,'

I know how to achieve this using the combination of the substr and indexOf methods:

str.substr(0, str.indexOf('D0*'))

Live demo: http://jsfiddle.net/simevidas/XSu22/

However, this is obviously not the best solution since it contains a redundancy (the str name has to be written twice). This redundancy can be avoided by using the match method together with a regular expression that captures the substring:

str.match(/???/)[1]

Which regular expression literal do we have to pass into match to ensure that the correct substring is returned?

My guess is this: /(.*)D0\*/ (and that works), but 开发者_高级运维my experience with regular expressions is rather limited, so I'm going to need a confirmation...


Try this:

/(.*?)D0\*/.exec(str)[1]

Or:

str.match(/(.*?)D0\*/)[1]

DEMO HERE

? directly following a quantifier makes the quantifier non-greedy (makes it match minimum instead of maximum of the interval defined). Here's where that's from


/^(.+?)D0\*/

Try it here: http://rubular.com/r/TNTizJLSn9


/^.*(?=D0\*)/

more text to hit character limit...


You can do a number-group, like your example.

/^(.*?)foo/

It mean somethink like:

  • Store all in group, from start (the 0)
  • Stop, but don't store on found foo (the indexOf)

After that, you need match and get

'hello foo bar foo bar'.match(/^(.*?)foo/)[1]; // will return "hello "

It mean that will work on str variable and get the first (and unique) number-group existent. The [0] instead [1] mean that will get all matched code.

Bye :)

0

精彩评论

暂无评论...
验证码 换一张
取 消