0

I'm having a problem in replacing chars in string using python's 3 regex. I am able to find the pattern occurrences, but I want to replace a char that appears as first in the pattern. Unfortunately I'm replacing the whole pattern. On the other hand - I might be wrong in using regex for this task at all. Here is what I have:

>>> my_table1='\nParametr JednostkaNormaGodzinaŚrednia(1)123456789101112131415161718192021222324 \nDwutlenek siarki (SO2) µg/m3 350 56 53 50 51 51 44 41 36 39 42 34 30 34 33 26 25 24 23 24 25 21 21 22 24 35 \nTlenek azotu (NO) µg/m3 30 30 27 29 44 98 192

What I want to do is to insert ',' or ';' between the numbers. I can not simply replace all spaces with comma as I do not want to split this part: \nDwutlenek siarki (SO2) µg/m3. So I figured to find occurrences of space and digits using regex (r'\s\d+'). This finds all instances correctly. Now I wanted to use the sub function to replace the \s with ',' but I do not know how to isolate just \s from the pattern. Any ideas?

1
  • in general, and especially with regex, it is wise to provide not only INPUT but also expected OUTPUT, this will help people help you. Commented Dec 27, 2012 at 13:01

1 Answer 1

3

Use lookbehind/lookahead, like this:

p = re.compile(r'(?<=\d)\s(?=\d)')
p.sub(';', my_table1)

Positive lookbehind (?<=\d) matches anything after a digit (\d) without matching the digit itself; \s matches a single whitespace character; and positive lookahead (?=\d) matches anything that is followed by a digit. So this replaces any single whitespace between two digits with a ;. Note that the lookbehind/ahead needs to be fixed length (so you can't use things like (?<=\d+)).

In your case it should be enough with just r'\s(?=\d)' though, may not need the lookbehind.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Anders, this fixed the problem. I did see it (lookbehind/ahead) in the doc's but couldn't get the mechanism. It's clear now. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.