S
S
ssneg2012-03-22 18:37:01
Programming
ssneg, 2012-03-22 18:37:01

To the RegExp gurus - how to reduce the number in a string?

Good afternoon!
I have a big XML. It has different tags, incl. like this: <*x>828<*/x> (several thousand). I want to move everything 120 points to the left, i.e. I need to replace the above line with <*x>708<*/x>.

My little experience as an unfulfilled programmer suggests that Notepad ++ and regular expressions will help me. But how exactly? Please help!

Thank you! :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Shein, 2012-03-22
@ssneg

In PHP:

<?php
$result = preg_replace_callback('/(<[^>]+>)(\d+)(<[^>]+>)/', function($matches) { return $matches[1] . ($matches[2] - 120) . $matches[3]; } , '<*x>828<*/x> <*x>120<*/x> <*x>5<*/x>');
var_dump($result);

string(37) "<*x>708<*/x> <*x>0<*/x> <*x>-115<*/x>"

PS You have some strange tags, usually the closing tag looks like </*x>, not <*/x>

I
IkaR49, 2012-03-22
@IkaR49

If what you have given is required verbatim, then immediately for notepad:
Find: (<\*x>)(828)(<\*\/x>)
Replace with: \1708\3

A
avalak, 2012-03-22
@avalak

XML on regular expressions ... nope.

# coding: utf-8

import codecs
from lxml import etree

ENCODING = 'utf-8'
XML_SOURCE_FILE = 'source.xml'
XML_OUT_FILE = 'source.out.xml'
VALUE = -120
TAG_NAME = 'id'

with codecs.open(XML_SOURCE_FILE, encoding = ENCODING) as xml_source:
  root = etree.parse(xml_source).getroot()

for tag in root.iter(TAG_NAME):
  tag.text = str(int(tag.text) + VALUE)

with codecs.open(XML_OUT_FILE, 'w', encoding = ENCODING) as xml_out:
  xml_out.write(etree.tostring(root, pretty_print = True, encoding = ENCODING, xml_declaration = True))

And don't forget xmllint for prevention.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question