使用正则表达式删除标题

时间:2018-08-24 07:02:13

标签: python regex

如何在字符串的开头删除2或3个字符,并在其后加一个点,并可以或不可以将其后跟一个空格?

i = 'mr.john'
i.replace("mr.","")

上面的代码正确地返回了名称“ john ”,但并非在所有情况下都正确。例如。

i = 'smr. john'
i.replace("mr.","")
's john'

预期结果为“ 约翰

3 个答案:

答案 0 :(得分:2)

如果您需要更通用的方法([INFO ] 2018-08-24T07:49:19,739Z [Node thread-1] flow.[c833dc79-501e-4484-9c43-a6924b472542].initiateSession - Initiating flow session with party O=CompanyC, L=Paris, C=FR. Session id for tracing purposes is SessionId(toLong=4256917187941908080). {} [WARN ] 2018-08-24T07:50:01,777Z [Messaging DLGQRf63MNQ2zpywoVzUZ3eBVB4Yp5oaA5aYSogUwzuCCA] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL2zA4g5QWv3dzx985Q9PMcvrNX4DUGv2pc7DcVjNgA8Hj,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.2-corda,platform-topic=platform.session,_AMQ_DUPL_ID=8473dd65-96e3-4a45-8076-92016a03c56c]] redelivery to internal.peers.DL2zA4g5QWv3dzx985Q9PMcvrNX4DUGv2pc7DcVjNgA8Hj {} [WARN ] 2018-08-24T07:50:01,808Z [Messaging DLGQRf63MNQ2zpywoVzUZ3eBVB4Yp5oaA5aYSogUwzuCCA] messaging.P2PMessagingClient.sendWithRetry - Reached the maximum number of retries (3) for message ClientMessageImpl[messageID=0, durable=true, address=internal.peers.DL2zA4g5QWv3dzx985Q9PMcvrNX4DUGv2pc7DcVjNgA8Hj,userID=null,properties=TypedProperties[platform-version=3,corda-vendor=Corda Open Source,release-version=3.2-corda,platform-topic=platform.session,_AMQ_DUPL_ID=66467ea0-56b9-4655-8311-f0806bf7fa97]] redelivery to internal.peers.DL2zA4g5QWv3dzx985Q9PMcvrNX4DUGv2pc7DcVjNgA8Hj {} 可能会有更多名称),则可以使用此代码。您可以定义自己的前缀以删除:

i

您可以实时here对其进行测试

创建的正则表达式是这样:

import re

prefixes = ['mr', 'smr']
regex = r'\b(?:' + '|'.join(prefixes) + r')\.\s*'
i = 'hi mr.john, smr. john, etc. Previous etc should not be removed'
i = re.sub(regex,'',i)
print(i)

答案 1 :(得分:1)

您想要在字符串的开头两个或三个字符,然后是一个点,然后是一个空格。作为正则表达式,它看起来像^\w{2,3}\. ?

现在您可以使用re.sub将此部分替换为空字符串。

cleaned_name = re.sub(r'(^\w{2,3}\. ?)', r'', name)

答案 2 :(得分:0)

使用public ConcurrentDictionary<TMessage, string> MessageList { get; set; } public Handler(ConcurrentDictionary<TMessage, string> messageList) { MessageList = messageList; } ... private void ReceivedMessages(TMessage Message) { MessageList.TryAdd(message, ""); } 进行切片。

例如:

str.find

输出:

i = 'smr. john'
print(i[i.find(".")+1:].strip())

i2 = 'mr.john'
print(i2[i2.find(".")+1:].strip())
相关问题