0

I believe this can be done with regex bux cant seem to find the correct syntax.

'SYS           W$_FIasdfLESTATXS               TABLE PARTITION           0    '

The third field in my file sometimes has space seperated output that needs to be converted to underscore seperated output so the above would become this.

'SYS           W$_FIasdfLESTATXS               TABLE_PARTITION           0    '

The third field is not always the same but when space seperated it will always have a single space. How can this be accomplished in python?

3
  • You may want to play with toy like rubular.com to practice your regexp skills. PS answer to your question is on that website in the tooltip ;) Commented Apr 28, 2015 at 15:46
  • see to check your syntax regexr.com Commented Apr 28, 2015 at 15:46
  • so if you do (\S \S) you can get 'E P' but i'm not sure how to reference that to replace it with E_P in this case. Any thoughts? Commented Apr 28, 2015 at 15:50

3 Answers 3

1

This is the REGEX you want : s/([^ ]) ([^ ])/\1_\2/g

In Python:

>>> import re
>>> my_string='SYS           W$_FIasdfLESTATXS               TABLE PARTITION           0    '
>>> re.sub(r'([^ ]) ([^ ])',r'\1_\2',my_string)
'SYS           W$_FIasdfLESTATXS               TABLE_PARTITION           0    '
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, didnt know how to backreference like that, This one also works re.sub(r'(\S) (\S)',r'\1_\2',x)
Your regex is better expressed as s/(\S)\s(\S)/\1_\2/g
1

Use a lookbehind and lookahead:

(?<=\w) (?=\w)

Or

(?<=\S)\s(?=\S)

Demo

In Python:

>>> s='SYS           W$_FIasdfLESTATXS               TABLE PARTITION           0    '
>>> re.sub(r'(?<=\S)\s(?=\S)', '_', s)
'SYS           W$_FIasdfLESTATXS               TABLE_PARTITION           0    '

Comments

0

use this pattern

(?<! ) (?! )

Demo

(?<!            # Negative Look-Behind
                # " " a white space
)               # End of Negative Look-Behind
                # " " a white space
(?!             # Negative Look-Ahead
                # " " a white space
)               # End of Negative Look-Ahead

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.