How to use regexp on file, line by line, in Python

后端 未结 7 1884
[愿得一人]
[愿得一人] 2020-12-30 00:24

Here is my regexp: f\\(\\s*([^,]+)\\s*,\\s*([^,]+)\\s*\\)

I\'d have to apply this on a file, line by line. The line by line is OK, simple reading from

相关标签:
7条回答
  • 2020-12-30 00:59

    You can try something like this :

    import re
    regex = re.compile("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)")
    with open("my_file.txt") as f:
        for line in f:
            result = regex.search(line)
    
    0 讨论(0)
  • 2020-12-30 01:00

    I have used this aproach:

    import re
    #Define the search term:
    pattern = f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)
    
    #Create an empty list:
    data = []
    
    #then
    
    for line in open(r'file.txt'):
        if line !='':  #<-- To make sure the whole file is read
            word = re.findall(pattFinder1, line)
            data.append(str(word))   
    
    0 讨论(0)
  • 2020-12-30 01:08
    import re
    with open('file.txt') as f:
        for line in f:
            match = re.search('f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)', line)
    

    Note that Python automatically compiles and caches the regex, so a separate compile step is not required in this case.

    0 讨论(0)
  • 2020-12-30 01:08

    use import re, then re.compile() with your pattern as an argument, and use the resulting object's match attribute on each line. something like this..

    import re 
    pat = re.compile(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)')
    for line in file:
      # use pat.match, pat.search .. etc
    
    0 讨论(0)
  • 2020-12-30 01:14

    The following expression returns a list; every entry of that list contains all matches of your regexp in the respective line.

    >>> import re
    >>> [re.findall(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line) 
                for line in open('file.txt')]
    
    0 讨论(0)
  • 2020-12-30 01:19
    for line in file:
       line = re
               .match("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)",line)
               .group(0)
    
    0 讨论(0)
提交回复
热议问题