2015-01-21 71 views
0

我有這樣的一個表:正則表達式來改變ASCII表格式

head1 | head2 | head3 
======================= 
foo=bar | baz | quuux 

是否有一個正則表達式,替換的等號用線劃的線,但保留在其他等號桌子?由破折號組成的線必須與由等號組成的線的長度相等。

預計輸出

head1 | head2 | head3 
----------------------- 
foo=bar | baz | quuux 

我使用Python重新庫。

+1

什麼是你期望的輸出?你正在運行哪種語言? – 2015-01-21 11:30:17

回答

1
=(?=={2,}|$) 

試試這個。更換-。參見demo。

https://regex101.com/r/tX2bH4/73

+2

因foo |而失敗bar | quu ==' – georg 2015-01-21 11:36:31

+0

@georg我猜測OP應該對它進行校驗。反正它的一個小修補 – vks 2015-01-21 11:37:14

+0

'{1,}'比'+'更長,更不便攜,並且可讀性更差。 – tripleee 2015-01-21 12:19:11

2

是否有一個正則表達式,替換的等號加上行破折號

我會做這樣的,

>>> import re 
>>> s = '''head1 | head2 | head3 
======================= 
foo=bar | baz | quuux''' 
>>> for i in s.split('\n'):    # Splits the input according to the newline character and iterate through the contents. 
     if re.match(r'^=+$', i):  # If the item has only equal signs then 
      print(i.replace('=', '-')) # replace = with - dashes 
     else: 
      print(i)     # else print the whole line 


head1 | head2 | head3 
----------------------- 
foo=bar | baz | quuux 
+0

你不需要'(?m)'修飾符 - 你已經在使用單行。否則,這就是我會做的。 – 2015-01-21 11:44:04

+0

是的,謝謝.... – 2015-01-21 11:44:31

1

的。如果你只有以==foo=bar開頭的行纔可以使用正常的str.replace。

s=""" 
head1 | head2 | head3 
======================= 
foo=bar | baz | quuux 
""" 
out = "" 

for line in s.splitlines(True): 
    if line.startswith("="): # or if line[0]== "=" 
     out += line.replace("=", "-") 
    else: 
     out += line 
print(out) 
head1 | head2 | head3 
----------------------- 
foo=bar | baz | quuux 

這應該覆蓋情況下,你只需要在該行=比正則表達式更高效:

for line in s.splitlines(True): 
    if not line.rstrip().translate(None,"="): # or if line[0]== "=" 
     out += line.replace("=","-") 
    else: 
     out += line 
print(out)