ryandlf
ryandlf

Reputation: 28555

Javascript Regex: Match Up to Or Between But Not Including

For instance, I am using a simple regex to match everything before the first space:

var str = '14:00:00 GMT';
str.match(/(.*?)\s/)[0]; //Returns '14:00:00 ' note the space at the end

To avoid this I can do this:

str.match(/(.*?)\s/)[0].replace(' ', '');

But is there a better way? Can I just not include the space in the regex? Another examle is finding something between 2 characters. Say I want to find the 00 in the middle of the above string.

str.match(/:(.*?):/)[0]; //Returns :00: but I want 00
str.match(/:(.*?):/)[0].replace(':', ''); //Fixes it, but again...is there a better way?

Upvotes: 2

Views: 3485

Answers (5)

John Woo
John Woo

Reputation: 263803

Try this,

.*(?=(\sGMT))

RegexBuddy ScreenShot

enter image description here

Upvotes: 0

Xiaodan Mao
Xiaodan Mao

Reputation: 1706

Your code is quite close to the answer, you just need to replace [0] with [1]. When str.match(/:(.*?):/) is executed, it returns an object, in this example, the object length is 2, it looks like this:

[":00:","00"]

In index 0, it stores the whole string that matches your expression, in index 1 and later, it stores the result that matches the expression in each brackets.
Let's see another example:

 var str = ":123abcABC:";
 var result = str.match(/:(\d{3})([a-z]{3})([A-Z]{3}):/);
 console.log(result[0]);
 console.log(result[1]);
 console.log(result[2]);
 console.log(result[3]);

And the result:

:123abcABC: 
123 
abc 
ABC

Hope it's helpful.

Upvotes: 0

turtledove
turtledove

Reputation: 25904

I think you just need to change the index from 0 to 1 like this:

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

0 means the whole matched string, and 1 means the first group, which is exactly what you want.

@codaddict give another solution.

str.match(/(.*?)(?=\s)/)[0]

(?=\s) means lookahead but not consume whitespace, so the whole matched string is '14:00:00' but without whitespace.

Upvotes: 2

codaddict
codaddict

Reputation: 455282

You can use positive lookahead assertions as:

(.*?)(?=\s)

which says match everything which is before a whitespace but don't match the whitespace itself.

Upvotes: 2

epoch
epoch

Reputation: 16615

Yes there is, you can use character classes:

var str = '14:00:00 GMT';
str.match(/[^\s]*/)[0]; //matches everything except whitespace

Upvotes: 1

Related Questions