2

given a file that looks like this:

mmm     55  v1235

mmm     111 v1241

mmm     22  v2453

mmm     1   v3464

mmm     555 v5353

I want the result to be ( replace all digits with white spaces):

mmm         v1235

mmm         v1241

mmm         v2453

mmm         v3464

mmm         v5353

Well I can find the length subtract and and turn to white space. can I do it in one line ?

something like that, but in sub second parameter is a string and not a regex:

new_line = re.sub(r'mmm \d+', r'mmm \s+', line)

3
  • 1
    Why not just: line = re.sub(r'\d', ' ', line); Commented May 10, 2017 at 8:19
  • @anubhava you are correct, sorry edited the question Commented May 10, 2017 at 8:24
  • ok in that case use: line = re.sub(r'\d(?=\d* )', ' ', line); Commented May 10, 2017 at 8:26

3 Answers 3

1

Using a lookahead you can check if a matching digit is followed by 0 or more digits and a space as:

line = re.sub(r'\d(?=\d* )', ' ', line);

RegEx Demo

(?=\d* ) is positive lookahead that asserts we have 0 or more digits and a space next to a matching digit.

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

Comments

0

new_line = re.sub(r'mmm\s\d+\s?v', 'mmm v', line)

Seems work?

Comments

0

You may put the mmm with 5 spaces into a lookbehind and process the match within a lambda expression:

import re
s = '''mmm     55  v

mmm     111 v

mmm     22  v

mmm     1   v

mmm     555 v'''
res = re.sub(r'(?<=mmm {5})[0-9]+', lambda x: " "*len(x.group()), s)
print(res)

See the Python demo.

The (?<=mmm {5})[0-9]+ pattern matches 1 or more digits that are preceded with mmm and 5 regular spaces. The lambda x: " "*len(x.group()) code replaces the digits with the same amount of spaces.

Or just wrap the two parts of the pattern with capturing groups and use .group(1) and .group(2):

res = re.sub(r'(mmm     )([0-9]+)', lambda x: "{}{}".format(x.group(1), " "*len(x.group(2))), s)

See another demo.

Comments

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.