0

In the example below I am trying to capture the text between the two asterixes.

var str="The *rain in SPAIN* stays mainly in the plain"; 
var patt1=/\*...\*/;
console.log(str.match(patt1));

I'm trying to follow the example here

http://www.regular-expressions.info/examples.html

\Q...\E Matches the characters between \Q and \E literally, suppressing the meaning of special characters.

But I am having trouble following along

Hoa
  • 19,858
  • 28
  • 78
  • 107
  • possible duplicate of [Regular Expression to find a string included between two characters, while EXCLUDING the delimiters](http://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclu) – Pranay Rana Jan 30 '12 at 08:32

4 Answers4

1

Try

var str="The *rain in SPAIN* stays mainly in the plain"; 
var patt1=/\*.*\*/;
console.log(str.match(patt1));

The \* means the literal "*" character. Then the . means any character and * means any number of times, so .* means "any number of characters".


Optional bonus:

The code above should work fine, but you'll notice that it matches greedily. So with input abcd*efgh*ijkl*mnop, the output will be *efgh*ijkl*, whereas you might have preferred the non-greedy match *efgh*.

To do this, use

var patt1=/\*.*?\*/;

The ? operator indicates non-greediness and ensures the least number of characters possible to get to the next \* are eaten, whereas without the ?, the most characters possible to get to the next \* are eaten.

To learn more I recommend http://www.regular-expressions.info/repeat.html . In particular read the "laziness instead of greediness" part.

Cam
  • 14,930
  • 16
  • 77
  • 128
1

Use .* and () to capture groups:

var str = "The *rain in SPAIN* stays mainly* in the plain"; 
var patt1 = /\*(.*)\*/;

console.log(str.match(patt1));

And the result:

["*rain in SPAIN* in the plain*", "rain in SPAIN* in the plain"]

If you use:

var patt1=/\*([^*]+)\*/;

the result will be:

["*rain in SPAIN*", "rain in SPAIN"]
Bon Espresso
  • 693
  • 3
  • 5
0

Why the three dots? ...

var str="The *rain in SPAIN* stays mainly in the plain"; 
var patt1=/\*.*\*/;
console.log(str.match(patt1));
Frankie
  • 24,627
  • 10
  • 79
  • 121
0

I'm not sure where you're seeing the ... in the example. a . is a single instance of any char (a wild card. So, in your example what you would need to do is this...

var patt1=/\*.*?\*/;

However you're going to get the * on both sides as part of your result.

You're searching for an actual *

then you're searching for any number of . (wild cards)... any number because * also means as many as you find

but the ? means that you should stop if you encounter the next thing

which in your case is a litteral * again.

so... to translate

ASTERISK(anything as many times at it happens until another)ASTERISK

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236