簡體   English   中英

正則表達式清理編號列表

[英]Regular Expression to Clean a numbered list

我剛剛開始玩Regex並且似乎有點卡住了! 我在TextSoap中使用多行編寫了批量查找和替換。 這是為了清理食譜,我有OCR'd,因為有成分和方向我不能改變“1”成為“1”,因為這可以重寫“1湯匙”為“1.湯匙”。

因此,我檢查了以下兩行(可能有額外的行)是否是使用此代碼作為查找的下一個序列號:

^(1) (.*)\n?((\n))(^2 (.*)\n?(\n)^3 (.*)\n?(\n))
^(2) (.*)\n?((\n))(^3 (.*)\n?(\n)^4 (.*)\n?(\n))
^(3) (.*)\n?((\n))(^4 (.*)\n?(\n)^5 (.*)\n?(\n))
^(4) (.*)\n?((\n))(^5 (.*)\n?(\n)^6 (.*)\n?(\n))
^(5) (.*)\n?((\n))(^6 (.*)\n?(\n)^7 (.*)\n?(\n))

以下作為上述各項的替代:

$1. $2 $3 $4$5

我的問題是雖然它按照我想要的方式工作,但它永遠不會執行最后三個數字的任務......

我要清理的文字示例:

1 This is the first step in the list

2 Second lot if instructions to run through
3 Doing more of the recipe instruction

4 Half way through cooking up a storm

5 almost finished the recipe

6 Serve and eat

而我希望它看起來像:

1. This is the first step in the list

2. Second lot if instructions to run through

3. Doing more of the recipe instruction

4. Half way through cooking up a storm

5. almost finished the recipe

6. Serve and eat

有沒有辦法檢查上面的一行或兩行以向后運行? 我看過前瞻和后視,我在那一點上有點困惑。 有沒有人有辦法清理我的編號清單或者幫我處理我想要的正則表達式?

dan1111是對的。 使用類似的數據可能會遇到麻煩。 但鑒於您提供的樣本,這應該工作:

^(\d+)\s+([^\r\n]+)(?:[\r\n]*) // search

$1. $2\r\n\r\n                 // replace

如果您不使用Windows,請從替換字符串中刪除\\r

說明:

^           // beginning of the line
(\d+)       // capture group 1. one or more digits
\s+         // any spaces after the digit. don't capture
([^\r\n]+)  // capture group 2. all characters up to any EOL
(?:[\r\n]*) // consume additional EOL, but do not capture

更換:

$1.       // group 1 (the digit), then period and a space
$2        // group 2
\r\n\r\n  // two EOLs, to create a blank line
          // (remove both \r for Linux)

那這個呢?

1 Tbsp salt
2 Tsp sugar
3 Eggs

您已經遇到了正則表達式的一個主要限制:當您的數據無法嚴格定義時,它們無法正常工作。 您可以直觀地知道什么是成分,什么是步驟,但要從算法到可靠的規則集並不容易。

我建議你考慮一種基於文件中位置的方法。 給定的食譜通常將所有食譜格式相同:例如,首先是成分,然后是步驟列表。 這可能是一種更容易區分的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM