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!

Toto
  • 89,455
  • 62
  • 89
  • 125
user1028096
  • 89
  • 1
  • 1
  • 2
  • 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? – Tim Pietzcker Nov 03 '11 at 16:16

4 Answers4

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
dallin
  • 8,775
  • 2
  • 36
  • 41
  • 1
    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); } – Kiechlus Apr 27 '16 at 12:43
  • Best answer because it does not produce errors in Safari either, since this regex does not use lookahead or lookbehind. – SlickRemix Jan 31 '22 at 20:39
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);
Sagar Mistry
  • 131
  • 11
0
"(.+)"$

Regular expression visualization

Edit live on Debuggex

This was asked in 2011.....

Community
  • 1
  • 1
progrenhard
  • 2,333
  • 2
  • 14
  • 14
0
"([^"\\]*(?:\\.[^"\\]*)*)"

I recommend reading about REGEXes here

a'r
  • 35,921
  • 7
  • 66
  • 67
Joao Figueiredo
  • 3,120
  • 3
  • 31
  • 40