Home > Enterprise >  Python regex to check new lines between strings
Python regex to check new lines between strings

Time:11-09

I have the following strings and need to have one line between y(age) and x(name) if multiple x,y presents , if we have only one x,y then no need to have a new line. whats the best way to use in python regex.

x:name
y:age

x:name
y:age

CodePudding user response:

Here is a regex replacement approach:

inp = """x:name
y:age

x:name
y:age"""

output = re.sub(r'(?<=\S)\n(?=\S)', r'\n\n', inp)
print(output)

This prints:

x:name

y:age

x:name

y:age

The regex pattern used here matches newlines which are surrounded on both sides by non whitespace characters:

  • (?<=\S) assert that what precedes is not whitespace
  • \n match a newline
  • (?=\S) assert that what follows is not whitespace

This regex logic allows us to target only newlines sandwiched in between content lines.

  • Related