Hello, how to get line matches as a variable,

pattern_get_GB = r'(\d{1,6}GB)' for line in first_rep_out.splitlines(): if re.search(pattern_get_GB, line) GB_1.append(first_rep_GB_match) print(GB_1) 

Clarification: if a match is found in a line, then it needs to be written into a variable and added to the list, at the entrance we have a bash command that goes by lines, in each line I look for the data I’ve received, if found, I need to add the data to the line.

PS: I know about this option:

 for line in first_rep_out.splitlines(): res = re.findall(pattern_get_GB, line) GB_1.append(res) print(GB_1) 

but there are blank lines in the output, how to skip them?

  • Who does "him" need to write to a variable? Give an example of the input data and what you want to get at the output - MaxU
  • Regular expression found a match in the line, how to write the result to a variable? - Merser5
  • 3
    You apparently do not understand, they tell you. what a coincidence, what lines? What are you talking about? Unclear! - And
  • one
  • one
    something tells me that you just need to: re.findall(pattern_get_GB, first_rep_out) without any cycles ... - MaxU

1 answer 1

If you do not want to add to the list for this, use the condition before the command (+ added logic if there are several or more than one matches):

 for line in first_rep_out.splitlines(): res = re.findall(pattern_get_GB, line) for r in res: if bool(res[0]): GB_1.append(res) print(GB_1) 

You can also filter the resulting list - get rid of the '' :

 print(filter(bool, GB_1) 

Execution Example:

 print(filter(bool, ["", "qwerty"]) # ["qwerty"] 

If you have the result of the following [[""], ["qwerty"]] then you will first have to extract from the lists:

 filter(bool, [x.pop() for x in r]) 
  • 1. if bool(res): - this is the same as if res: in the if condition in the internal loop, bool also not needed. 2. This check is unnecessary, because if the res list is empty, the loop will never be executed. 3. Apparently, the original regular expression does not match the empty string (correct me if I am mistaken), so the condition in the inner loop is not needed, and the inner loop itself is not very necessary. - insolor