簡體   English   中英

Python 中的正則表達式,用於根據以 @ 開頭並以:結尾的字符拆分字符串:?

[英]Regular expression in Python to split a string based on characters that begin with @ and end with :?

我有看起來像這樣的字符串:

sentences = "@en:The dog went for a walk@es:El perro fue de paseo" 

所需的 output:

splitted = ['The dog went for a walk', 'El perro fue de paseo']

當前代碼:

splitted = re.split("^@:$", sentences)  

因此,id 喜歡根據以添加符號@開頭並以冒號:結尾的字符來拆分句子,因為這些是所有語言的編碼方式,例如 (@en:, @es:, @fr:, @nl : ETC。)

您可以使用否定字符 class 從 @ 拆分為:而不匹配任何這些字符。

結果中可能有空條目,您可以將其過濾掉。

@[^@:]*:

正則表達式演示

import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
splitted = [s for s in re.split("@[^@:]*:", sentences) if s]

print(splitted)

Output

['The dog went for a walk', 'El perro fue de paseo']

你好試試這個代碼它會幫助你

import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo" 
splitted = re.split(r"@[a-zA-z]+:",sentences)  
print(splitted)

你需要這個正則表達式: @[^@:]+:

首先, @匹配一個@

接下來, [^@:]+匹配任意數量的字符(最少一個)不是@:

最后, :匹配一個:

import re
sentences = "@en:The dog went for a walk@es:El perro fue de paseo"
splitted = re.split("@[^@:]+:", sentences)
print(splitted[1:])

output:

['The dog went for a walk', 'El perro fue de paseo']

暫無
暫無

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

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