私信  •  关注

Allan

Allan 最近创建的主题
Allan 最近回复了
6 年前
回复了 Allan 创建的主题 » 如何在python中获取regex中的组[duplicate]

代码 :

import re

regexPattern = r"(\d+)"
expression = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"
print(re.findall(regexPattern,expression))

输出 :

['1123', '45', '35', '99']

在当前代码中,将出现错误:

    print("Second group : ", matchValue.group(2))
IndexError: no such group

因为只有 一组 在正则表达式中。

通过以下方式更改代码,并在 https://regex101.com/r/BjTrgU/2 ,您将有一个单独的匹配项(整行)和四个组,您可以单独访问它们来提取数字。

区分匹配(当regex匹配/验证输入字符串时)和存储在regex组中的值(每个组都由括号定义)之间的区别是很重要的 ()

第1次出现 () 在regex中可以通过backreference访问 \1 在regex(或替换字符串)中,或者 group(1) 在regex之外,第二次出现 () 在regex中可以通过backerefence访问 \2 在regex(或替换字符串)中,或者 group(2) 在regex之外,。。。

import re

class Test3:

    def printAllGroups(self):
        regexPattern = r"^(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+$"
        text = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"
        matcher = re.compile(regexPattern, flags=re.IGNORECASE)
        matchValue = matcher.match(text);
        if matchValue:
            print("First group : ", matchValue.group(1))
            print("Second group : ", matchValue.group(2))
            print("Third group : ", matchValue.group(3))
            print("Third group : ", matchValue.group(4))

if __name__ == '__main__':
    test3 = Test3()
    test3.printAllGroups()

输出:

python test3.py
('First group : ', '1123')
('Second group : ', '45')
('Third group : ', '35')
('Third group : ', '99')
6 年前
回复了 Allan 创建的主题 » Python:如何使用regex显示文本文件中的前几个数字

您可以使用以下代码:

#open the 2 files in read mode
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
  data = f1.read() + f2.read() #store the content of the two files in a string variable
  lines = data.split('\n') #split each line to generate a list
  #do the sorting in reverse mode, based on the 3rd word, in your case number of views
  print(sorted(lines[:-1], reverse=True, key=lambda x:int(x.split()[2])))

输出:

['file GameOfThrones 900 0', 'file DC/Batman 504 1', 'file Science/Chemistry 444 1', 'file Marvel/CaptainAmerica 342 0', 'file Math/Calculus 342 0', 'file Psychology 324 1', 'file Marvel/GuardiansOfGalaxy 300 1', 'file Anthropology 234 0', 'file DC/Superman 200 1', 'file Science/Biology 200 1']
6 年前
回复了 Allan 创建的主题 » python regex将括号限制为一次

你很快就能让你的代码工作了。 您只需将样本调整为:

import re

number=input("Please enter phone number:  " )
x=re.match('^([(+*)]\d{3}[(+*)][a-]\d{3}[a-]\d{4})$', number)
if (x):
  print("Perfect! Your format is valid: -->  " "'"+number+"'")
else:
  print("Not a valid format, please enter as (###)-###-####")

在哪里,而不是使用 findall ,你使用 match 因为您正在检查这个数字是否与模式(regex)相关,而且您不想从中提取一些子信息。

你还需要添加锚( ^ , $ )在正则表达式中强制输入字符串开头或结尾不包含其他字符。

输出:

Please enter phone number:  '(111)-111-1111'
Perfect! Your format is valid: -->  '(111)-111-1111'
Please enter phone number:  '(((((111)-111-1111'
Not a valid format, please enter as (###)-###-#