SS-Salt
SS-Salt

Reputation: 139

Javascript extract strings that match regex from text

I'm trying to get a set of strings from a paragraph that match the format of 4chan's quotes: >>1111111 where it starts with >> followed by 7 digits.

>>1111000
>>1111001
Yes, I agree with those sentiments. 

Both >>1111000 and >>1111001 would be extracted from the text above which I would then split into the digits after.

Upvotes: 0

Views: 118

Answers (4)

benhatsor
benhatsor

Reputation: 2033

Like @spyshiv said, you can match the string like so:

var string = '>>1111000';
var matches = string.match(/[>]{2}[0-1]{7}/);
console.log(matches);

Upvotes: 0

Flo H
Flo H

Reputation: 59

There appears to be some answers, but since it's a topic I would like to understand better here are my two cents. In the past this answer has helped me a lot and online regex sites are also great, such as this one

 

      <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Parse Test</title>
    
    </head>
    <body>
        <div >
            <text id="ToParse">
    
                >>1111000 <br>
                >>1111001 <br>
                Yes, I agree with those sentiments.
    
            </text>
        </div>
    
    <script>
    
     try {
        var body = document.getElementById('ToParse').innerHTML;
        console.log(body);
    
    
    } catch (err) {
        console.log('empty let body,' + " " + err);
    }
    
    
    function parseBody () {
    
        // from HTML
    // function parseBody (body) {
        // const regex = /(&gt;&gt;)([0-9]*)\w+/gm;
    
        // from JS
        const regex = /(>>)([0-9]*)\w+/gm;
        const body = `            >>1111000 <br>
                    >>1111001 <br>
                    Yes, I agree with those sentiments.`;
    
        let m;
    
        while ((m = regex.exec(body)) !== null) {
            // This is necessary to avoid infinite loops with zero-width matches
            if (m.index === regex.lastIndex) {
                regex.lastIndex++;
            }
    
            // The result can be accessed through the `m`-variable.
            m.forEach((match, groupIndex) => {
                console.log(`Found match, group ${groupIndex}: ${match}`);
            });
        }
    
    };
    
    parseBody(body);
    
    
    
    
    // </script>
    
    
    
    
    </body>
    </html>

Upvotes: 0

spyshiv
spyshiv

Reputation: 178

You can use this regex

/[>]{2}[0-1]{7}/

Upvotes: 1

Brian Lee
Brian Lee

Reputation: 18187

You can use the following which will match lines starting with 2 > characters followed by 7 digits:

const regex =/^[>]{2}[\d]{7}$/gm;

const text = `>>1234567
>>6548789
foo barr`;

const matches = text.match(regex);

console.log(matches);

Upvotes: 1

Related Questions