Skip to content Skip to sidebar Skip to footer

Replace Single Space But Not Multiple Space Python

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

Solution 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    '

Solution 2:

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    '

Solution 3:

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

Post a Comment for "Replace Single Space But Not Multiple Space Python"