为了账号安全,请及时绑定邮箱和手机立即绑定

使用正则表达式从“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条经验 获得超7个赞

您正在查找数字之间的一个或多个非空格'\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 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信