Home > Blockchain >  NodeJS - Regex to match a specific string containing numbers (Closed)
NodeJS - Regex to match a specific string containing numbers (Closed)

Time:12-21

Say I have a file called test.txt which is fixed with nonsense text.

But among this text is a specific string containing numbers in single quotes ('') like so;

blahblahblah: 
Blahblahblah:
targetNumber: '30' <== target numbers
Blahblahblah

How would I go about replacing only these single quoted numbers, without replacing the entire file contents like so;

blahblahblah: 
Blahblahblah:
targetNumber: '22' <== changed numbers
Blahblahblah

So far the regex functions I've constructed using numerous other questions on StackOverflow don't seem want to work and if they do work, they don't work as expected because they always seem to replace the entire contents of the file rather than just that set of numbers.

My last regex attempt on this is below, but it doesn't work, it just replaces the entire file contents so I don't where I'm going wrong, I'm still learning regex currently, can anyone please help???


var folder = "just/a/test/folder";

fs.readFile(path.join(folder, 'test.txt'), 'utf8', (error, data) => {
    if (error) {
        console.log('Unable to Read File');
        return;

    };

    var regex = /'\d{1,2}\'/
    var str = data.substring(data.indexOf("targetNumber: ")   14);
    var m = str.match(regex)

    var replace = str.replace(m[1], "22");
    
    fs.writeFile(path.join(folder, 'test.txt'), replace, 'utf8', (error) => {
    if (error) {
        console.log('Modifying File failed')
        return;
    }
});

CodePudding user response:

You should do the replacement over the data and then you can capture targetNumber: in a group, using that group again with $1 in the replacement followed by your replacement.

See the match and the replacement at this regex demo.

const folder = "just/a/test/folder";
const file = 'test.txt'

fs.readFile(path.join(folder, file), 'utf8', (error, data) => {
    if (error) {
        console.log('Unable to Read File');
        return;

    }
    const regex = /\b(targetNumber:\s*')\d{1,2}'/g;
    const replace = data.replace(regex, "$122'");
    
    fs.writeFile(path.join(folder, file), replace, 'utf8', (error) => {
        if (error) {
            console.log('Modifying File failed')
        }
    });
});

CodePudding user response:

A basic regex replacement should work. Assuming the replacement for the target number always be 22, you could try:

var input = `blahblahblah: 
Blahblahblah:
targetNumber: '30'
Blahblahblah`;

var output = input.replace(/'\d '/g, "22");
console.log(output);

  • Related