Algorithms, Blockchain and Cloud

How to Search and Replace using Regular Expression with Arithmetic Evaluation?


Let’s consider this XML data, and you want to add an offset to all Z coordinate.

<data>
  <point>
    <x>
        1
    </x>
    <y>
        2
    </y>
    <z>
        3
    </z>
  </point>
  <point>
    <x>
        4
    </x>
    <y>
        5
    </y>
    <z>
        6
    </z>
  </point>
</data>

So the first thing is to search for these values wrapped in the Z tag, you can do this easily:

/\<z\>(.*)\</z\>/gi

Regular Expression

The (.*) match any character and it can be later referenced as \1. So, in sublime text editor, you could press Ctrl + H to invoke the search and replace tool.

However, the RegEx does not provide Arithmetic Evaluation if you want to do some simple math expressions to \1, \2 etc. But you can write a PHP script easily, with the preg_replace_callback function:

<?php
// shift.php
// https://helloacm.com/how-to-search-and-replace-using-regular-expression-with-arithmetic-evaluation/

if ($argc < 2) {
	die();
}
if (!is_file($argv[1])) {
	die();
}

// PHP 7.x null operator
$offset = $argv[2] ?? 0;

// Search and Replace using Regular Expression with Arithmetic Evaluation
echo preg_replace_callback(
        '~\<z\>(.*)\</z\>~i', // pattern for Z coordinate
        function ($matches) {
        	global $offset;
        	return "<z>".($matches[1] + $offset)."</Z>";
        },
        file_get_contents($argv[1])
);

To use this PHP script, simply type at command line e.g.

php shift.php data.xml 1.0 > new_data.xml

This will redirect the modified data from console to the file.

–EOF (The Ultimate Computing & Technology Blog) —

389 words
Last Post: What is DDOS and How do you Cope with DDOS Attacks?
Next Post: How to Respond with 503 Service Busy to Requests when Server Load Average is High?

The Permanent URL is: How to Search and Replace using Regular Expression with Arithmetic Evaluation? (AMP Version)

Exit mobile version