8

I need help with regex. I need to create a rule that would preserve everything between quotes and exclude quotes. For example: I want this...

STRING_ID#0="Stringtext"; 

...turned into just...

Stringtext 

Thanks!

1
  • 3
    More info needed: Can there be more than one quoted string in your input? Can there be escaped quotes? Which regex engine are you using? Commented Nov 3, 2011 at 16:16

4 Answers 4

4

The way to do this is with capturing groups. However, different languages handle capturing groups a little differently. Here's an example in Javascript:

var str = 'STRING_ID#0="Stringtext"'; var myRegexp = /"([^"]*)"/g; var arr = []; //Iterate through results of regex search do { var match = myRegexp.exec(str); if (match != null) { //Each call to exec returns the next match as an array where index 1 //is the captured group if it exists and index 0 is the text matched arr.push(match[1] ? match[1] : match[0]); } } while (match != null); document.write(arr.toString()); 

The output is

Stringtext 
Sign up to request clarification or add additional context in comments.

2 Comments

You can do this shorter: let result = []; let regex = /myRegex/g; let match = regex.exec(data); while(match) { result.push(match[1]); match = regex.exec(data); }
Best answer because it does not produce errors in Safari either, since this regex does not use lookahead or lookbehind.
1

Try this

function extractAllText(str) { const re = /"(.*?)"/g; const result = []; let current; while ((current = re.exec(str))) { result.push(current.pop()); } return result.length > 0 ? result : [str]; } const str =`STRING_ID#0="Stringtext"` console.log('extractAllText',extractAllText(str)); document.body.innerHTML = 'extractAllText = '+extractAllText(str);

Comments

0
"([^"\\]*(?:\\.[^"\\]*)*)" 

I recommend reading about REGEXes here

2 Comments

That doesn't remove the quotes from around the string.
Ouch, don't know how I forgot about it. But Tim Pietzcker is right, user should specify the REGEX engine
0
"(.+)"$ 

Regular expression visualization

Edit live on Debuggex

This was asked in 2011.....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.