2015-03-13 45 views
0
source= "<br />, systemd-system.conf(5), locale.conf(5),<br />  systemctl(1), journalctl(1), systemd-notify(1), daemon(7),sd-<br />  daemon(3), systemd.unit(5), systemd.special(5), pkg-config(1), kernel-<br />  command-line(7), bootup(7), systemd.directives(7)" 
source= sub(compile(r"([\, ]+)(?:([A-Za-z\.\-]+))?(?:(<br /> {7}))?([A-Za-z\.\-]*)(\([0-9]\))", DOTALL), r"\1[\2]\3[\4\5]", source) 

有了這個,我得到無與倫比的組錯誤。
但在regex101.com這給條件組替代

<br />, [systemd-system.conf][(5)], [locale.conf][(5)],[]<br />  [systemctl(1)], [journalctl][(1)], [systemd-notify][(1)], [daemon][(7)],[sd-]<br />  [daemon(3)], [systemd.unit][(5)], [systemd.special][(5)], [pkg-config][(1)], [kernel-]<br />  [command-line(7)], [bootup][(7)], [systemd.directives][(7)] 

結果,並不完全是一個我期待。
我需要

<br />, [systemd-system.conf(5)], [locale.conf(5)],<br />  [systemctl(1)], [journalctl(1)], [systemd-notify(1)], [daemon(7)],<br />  [sd-daemon(3)], [systemd.unit(5)], [systemd.special(5)], [pkg-config(1)], <br />  [kernel-command-line(7)], [bootup(7)], [systemd.directives(7)] 

測試on regex101.com

回答

1

我認爲你做了它對複雜的,試試這個:

r"([A-Za-z\.\-]+\([0-9]\))", r"[\1]" 

它尋找string-with.extras(5)和簡單地[ ]

如果圍繞它你想刪除一些不匹配這個正則表達式的字符(如在),您可以使用結果的第二個:

r"([^[])[A-Za-z\.\-]+", r"\1" 

將採取不具有[之前刪除任何string-with.extras

1

謝謝兩位。
我到了那裏(第5版),但我在我的代碼獲得無與倫比的組錯誤。

加入解決|只是在前面的標籤(版本7)。

+0

你有兩個答案無可匹敵的組,因爲它是不可能與我的,因爲所有組是強制性的(沒有'(?:)') – Math 2015-03-13 12:06:12

+0

如果
未找到,我只有一個組。這將由Python的3.5版本解決。 http://python.readthedocs.org/en/latest/library/re.html - 版本3.5中更改:不匹配的組被替換爲空字符串。 – Mauricio 2015-03-13 12:29:05

+0

這是jimmy_keen的正則表達式的問題,有什麼關於我的(數學),這是你想要的東西太簡單了? – Math 2015-03-13 12:56:06