Running Turtle
Running Turtle

Reputation: 12752

regex when format is not fixed

I have an output which structure varies (nbr of spaces before and after the equal sign, single quote or double quote)

 product description = "flsdfjldsjs fd fs"
 product description="fdsfsd"
 product description =""
 product description ='lfjdsdljfldsf'
 product description =''
 product description='fldsjfl'
 product description=''
 etc ...

How can i use regex to match the string between the quotes or the empty string ?

Upvotes: 0

Views: 80

Answers (4)

alex
alex

Reputation: 490453

Match it with...

str.match(/(['"])(.*?)\1/);

RegExr.

Upvotes: 2

yogsototh
yogsototh

Reputation: 15101

This will match the string with the quotes:

/['"].*['"]/ 

To match only what is inside you should use groups.

/['"](.*)['"]/

Which you use like this:

var myString = "position='abc de f'";
var myRegexp = /['"](.*)['"]/;
var match = myRegexp.exec(myString);
alert(match[0]);  // abc de f

Upvotes: 0

Diego
Diego

Reputation: 18359

Coffee is right, but to make it more specific, you can try:

var reg = /^product description *= *(("[^"]*")|('[^']*')) *$/

That way you don't run into problems if you encounter " inside ' or viceversa, as in "John's" or '"hi"'.

Upvotes: 0

mathematical.coffee
mathematical.coffee

Reputation: 56935

You can do:

^product description *= *['"](.*?)['"] *$

And the string is in capturing group 1.

The * before and after the = sign means "any number of spaces", and the ['"] means "match a " or a '".

Upvotes: 0

Related Questions