Skip to main content
 首页 » 编程设计

Python 正则表达式 : (\w+) not picking up up numbers with 2 digits or less

2025年05月04日25lvdongjie

我正在尝试使用 python 的正则表达式来识别来自用户的 3 个标记,它们都可以由字母或数字组成。

这是我使用的代码:

    match = re.search(r'(\w+)(\w+)(\w+)', inputStr) 
    if not match: 
        print("Not valid") 
    else: 
        numWord1 = match.group(0) 
        numword2 = match.group(1) 
        numWord3 = match.group(2) 
 
    print(num1) 

其中 inputStr 来自 raw_input()。我运行了我的代码,这是我从每个输入中得到的结果

      I typed: 1 2 3 
      I got: Not valid 
 
      I typed: 11 22 33 
      I got: Not valid 
 
      I typed: 111 222 333 
      I got: 111 
 
      I typed: 1 hello 3 
      I got: hello 
 
      I typed: hello 2 3 
      I got: hello 

我认为\w 匹配任何字母、数字或下划线,通过包含 + 我会在我的组中获得 1 个或多个它的实例。

请您参考如下方法:

\w 不匹配数字之间的空格——正如您正确指出的那样,\w 匹配字母、数字或下划线,但不匹配一个空格。尝试:

match = re.search(r'(\w+)\s+(\w+)\s+(\w+)', inputStr) 

\s+ 匹配数字组之间的一个或多个空白字符。

示例 在 Python 3 中测试:

>>> print(re.search(r'(\w+)\s+(\w+)\s+(\w+)',input('? ')).group(1)) 
? 1 2 3 
1