非正則表達式解決方案是相當平凡的:
start, _, end = text.rpartition('(')
result = start or end
rpartition
將結束搜索的字符串,並在第一(
返回三重(text-before, separator, text-after)
其中separator = '('
在這種情況下。如果字符串中沒有(...)
,則說明所有內容都在text-after
之內,並且text-before
和separator
都是空字符串。 當出現(...)
時,您將在text-before
的最後一個(
之前獲得所有文本,分隔符爲(
,text-after
將爲...)
。
因此start or end
總是包含您需要的值。如果start
不是你想要的,否則結果在end
。
或者:
result = next(filter(None, text.rpartition('(')))
樣品運行:
In [1]: texts = [
...: 'Homo sapiens (human)',
...: 'mitochondrion Capra hircus (goat)',
...: 'Escherichia coli',
...: 'Xenopus (Silurana) tropicalis (western tree frog)',
...: ]
In [2]: for text in texts:
...: start, _, end = text.rpartition('(')
...: print('in {!r}\t->\t{!r}'.format(text, start or end))
...:
in 'Homo sapiens (human)' -> 'Homo sapiens '
in 'mitochondrion Capra hircus (goat)' -> 'mitochondrion Capra hircus '
in 'Escherichia coli' -> 'Escherichia coli'
in 'Xenopus (Silurana) tropicalis (western tree frog)' -> 'Xenopus (Silurana) tropicalis '
In [3]: for text in texts:
...: print('in {!r}\t->\t{!r}'.format(text, next(filter(None, text.rpartition('(')))))
in 'Homo sapiens (human)' -> 'Homo sapiens '
in 'mitochondrion Capra hircus (goat)' -> 'mitochondrion Capra hircus '
in 'Escherichia coli' -> 'Escherichia coli'
in 'Xenopus (Silurana) tropicalis (western tree frog)' -> 'Xenopus (Silurana) tropicalis '
時序:
In [13]: texts *= 1000
In [14]: %%timeit
...: results = []
...: for text in texts:
...: start, _, end = text.rpartition('(')
...: results.append(start or end)
...:
1000 loops, best of 3: 1.04 ms per loop
其比基於正則表達式的溶液快4倍以上:
In [15]: import re
In [16]: %%timeit regex = re.compile(r'^(?:(?!.*\(.*\)).*|.*(?= \(.*\)))')
...: results = []
...: for text in texts:
...: match = regex.match(text)
...: results.append(match.group(0))
...:
100 loops, best of 3: 4.27 ms per loop
的filter
版本比or
解決方案稍慢:
In [19]: %%timeit
...: results = []
...: for text in texts:
...: results.append(next(filter(None, text.rpartition('('))))
...:
1000 loops, best of 3: 1.89 ms per loop
必須解決的一個正則表達式來實現?做一次「足夠接近」的比賽通常會更容易,然後做一些進一步的處理,比如在比賽結束時剝去括號內的任何東西。 –
@BryanOakley,如果我理解正確,根據第三個例子,它應該匹配。 – ndn
@ndn:謝謝。我不知何故錯過了看第三個例子。我已更新我的評論。 –