亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用正則表達式從“1.hello”獲取“hello”

使用正則表達式從“1.hello”獲取“hello”

繁星點點滴滴 2023-10-11 20:00:29
我剛剛學習正則表達式,但無法從列表中獲取單詞從這樣的列表中:[ "1. hello - jeff", "2. gello - meff", "3. fellow - gef", "12. willow - left"]我想檢索單詞:“hello”、“gello”、“fellow”和“willow”這是到目前為止我的簡化代碼for i in [ARRAY OF LISTED WORDS]:   word = re.findall(r'^((?![0-9]?[0-9]. ))\w+', i)     print(word)
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

您正在查找數字之間的一個或多個非空格'\S+'),后跟句點,后跟空格 ( '\d+\.\s'),以及空格后跟短劃線 ( '\s-'):

pattern = r'\d+\.\s(\S+)\s-'
[re.findall(pattern, l)[0] for l in your_list]


查看完整回答
反對 回復 2023-10-11
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

你的正則表達式模式:


pattern = r"""

    \d+     # 1 or more digits

    \.      # Escaped period character

    \s+?    # 1 or more whitespace

    (\w+)   # 1 or more alphabetic characters

    \s+     # 1 or more whitespace

    -       # hyphen

    .*      # zero or more of anything besides newline.

"""

字符串列表:


words = [ "1. hello - jeff", "2. gello - meff", "3. fellow - gef", "12. willow - left"]



for word in words:

    # capture results in a variable

    # re.X for verbose pattern format.

    tmp = re.search(pattern, word, flags = re.X)

    # If variable is not None, print results of the first captured group.

    if tmp:

        print(tmp.group(1))

輸出:


hello

gello

fellow

willow


查看完整回答
反對 回復 2023-10-11
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號