searching1
searching1

Reputation: 87

Python building a Regex pattern?

I'm working with this code and I'm having a hard time finding the correct pattern for this. I can achieve this by altering doing re.sub but I want to match without using re.sub if possible.

var = "77777 11111 12891 22222 i"
  1. From var I want to get only 11111. Like my code:

    ppat = re.findall(r'(77777 (?:[\d]{1,6}))', var)
    
  2. From var I want to get the 22222 before the "i" like this:

    opat = re.findall(r'((?:[\d]{1,6}) i)', var)
    
  3. How do I match these 2 patterns? For example, I'm putting different output to variable which will be matched by the patterns?

a. 1st possible output is:

output = "ndescr:  XXXX"

b. What pattern should I use to match the XXXX and instance that output variable appears like this and I want to get only the No entries. What regex pattern should I use?

output = "%  No entries found for the selected source(s)" 

Thanks

Upvotes: 0

Views: 377

Answers (2)

The Matt
The Matt

Reputation: 1724

While it is not completely clear what you are trying to match, I am giving it a shot.

If you are just trying to get the second and last element, then this can be done without regular expressions.

var = "77777 11111 12891 22222 I"

elements = var.split(" ") # Take the string, and split it into a list on spaces.

first_number = elements[1] # Get the second element ("11111").

second_number = elements[-2] # Get the second element from the end ("22222").

Alternatively, if you really want to use regular expressions or are looking for the number after 77777 a regular expression like this would work:

import re
var = "77777 11111 12891 22222 I"

# Finds the 5 numbers that follows a "7" repeated 5 times (with a space in between).
first_number = re.search("(?<=7{5}\s)\\d{5}", var).group()

# Find the 5 numbers that precedes an "I" (with a space in between).
second_number = re.search("\\d{5}(?=\sI)", var).group()

Upvotes: 1

goudan
goudan

Reputation: 58

re.findall("(?<=77777)\\s+(?:\\d{1,6})",var)
re.findall("(?:\\d{1,6})\\s+(?=i)",aa)

you can read python re module for details. enter link description here

Upvotes: 0

Related Questions