2017-12-05 4 views
-2

テキストを抽出してRegExでクリーンアップします。Python RegExは新しい行を削除します(そこには存在してはいけません)

私は基本的な正規表現を学んだが、この1を構築する方法がわからなかった。

str = ''' 
this is 
a line that has been cut. 
This is a line that should start on a new line 
''' 

はこれに変換する必要があります。

str = ''' 
this is a line that has been cut. 
This is a line that should start on a new line 
''' 

これr'\w\n\w'はそれをキャッチするようだが、わからないどのように新しい行をスペースで置き換え、単語の末尾と先頭には触れないでください

+0

を*なぜ*それは結果でなければなりませんか?どのような改行が削除されるか(それを実装する方法ははるかに少ない)の基準は何ですか? –

+0

あなたがLinux環境にいる場合は、 https://stackoverflow.com/questions/3134791/how-do-i-remove-newlines-from-a-text-file –

答えて

3

このlookbehind正規表現はre.subのために使用できます:

本の
>>> str = ''' 
... this is 
... a line that has been cut. 
... This is a line that should start on a new line 
... ''' 
>>> print re.sub(r'(?<!\.)\n', '', str) 
this is a line that has been cut. 
This is a line that should start on a new line 
>>> 

RegEx Demo

(?<!\.)\nマッチドットによって先行されていないすべての改行。

あなたはドットの存在に基づいて、試合はその後、使用したくない場合は、次の

re.sub(r'(?<=\w\s)\n', '', str) 

RegEx Demo 2

+0

hmm ..私がhttps://を持っている場合にうまく動作しないrepl.it/@Norfeldt/SuperficialCumbersomeTenrec – Norfeldt

+0

このリンクでは、元の文字列は表示されません。また、 'r '(?<!\。)\ n"を提案しましたが、そこに '\ w'もあります。 – anubhava

+1

私は知っている..ごめんなさい..私の例は私のユースケースをカバーすると思った。それはしませんでした。私は '\ w'を追加しなければなりませんでした。そうでないと奇妙な場所が追加されます。 – Norfeldt

関連する問題