![](/img/trans.png)
[英]remove text between parenthesis and change the position of words inside a string
[英]split string according to words between square parenthesis
我想使用正則表達式拆分字符串。
對於前。
val = "[python] how to [css]"
val = "[python][css] how to"
val = "how to [python][css]"
我的字符串看起來像這樣(嘗試對值字符串顯示不同的方式),我想像這樣拆分:
a=['python','css'] #(type list)
b="how to" #(type string)
我試過了
import re
pat = re.compile(r'(\w+\s*)')
re.findall(pat,val)
輸出:
['python', 'how ', 'to ', 'css']
我的正則表達式有什么問題?
x="[python] how to [css]"
print re.findall(r"(?<=\[)[^\]]*(?=\])",x) # this is the list you want
print re.sub(r"\[[^\]]*\]","",x) # this is the string you want
嘗試這種方式。您可以同時具有列表和字符串。
你可以試試
import re
val = "[python] how to [css]"
m = re.findall(r'\[(\w*)\]', val)
print m
# ['python', 'css']
\\[(\\w*)\\]
將匹配方括號內的所有單詞
從問題a=['python','css'] #(type list)
獲得了第一部分
>>> import re
>>> val = "[python] how to [css]"
>>> [i[1:-1] for i in re.findall("(\[[^\]]*\])", val)]
['python', 'css']
>>> val = "[python][css] how to"
>>> [i[1:-1] for i in re.findall("(\[[^\]]*\])", val)]
['python', 'css']
>>> val = "how to [python][css]"
>>> [i[1:-1] for i in re.findall("(\[[^\]]*\])", val)]
['python', 'css']
第二部分:(根據vks解決方案更新)
>>> re.sub(r"\[[^\]]*\]","",val)
'how to '
正則表達式(\\w+\\s*)
與[A-Za-z0-9_]
匹配,后跟0個或多個空格,因此它將與[python]
和[css]
中的css
和python
匹配。 此正則表達式: (\\w+\\s+)
符合您的要求。
您可以執行以下操作:
import re
pat = re.compile(r'\[(.*)\]')
re.findall(pat,val) # wil return ['python', 'css']
現在,您可以從相反的正則表達式獲取其余內容(匹配不在[
和]
之間的所有內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.