I am using this \d{2}-\d{2}-\d{4}
to validate my string. It works to pull the sequence of numbers out of said string resulting in 02-01-1716 however, i also need to pull the letter the string begins with and ends with; i.e. Q:\Region01s\FY 02\02-01-1716A.pdf i need the Q as well as the A so in the end i would have Q: 02-01-1716A
CodePudding user response:
You can use
import re
regex = r"^([a-zA-Z]:)\\(?:.*\\)?(\d{2}-\d{2}-\d{4}[a-zA-Z]?)"
text = r"Q:\Region01s\FY 02\02-01-1716A.pdf"
match = re.search(regex, text)
if match:
print(f"{match.group(1)} {match.group(2)}")
# => Q: 02-01-1716A
See the Python demo. Also, see the regex demo. Details:
^
- start of string([a-zA-Z]:)
- Group 1: a letter and:
\\
- a backslash(?:.*\\)?
- an optional sequence of any chars other than line break chars as many as possible, followed with a backslash(\d{2}-\d{2}-\d{4}[a-zA-Z]?)
- Group 2: two digits,-
, two digits,-
, four digits, an optional letter.
The output - if there is a match - is a concatenation of Group 1, space and Group 2 values.
CodePudding user response:
You can try:
(.).*(.)\.[^\.] $
Or with the validation:
(.).*\d{2}-\d{2}-\d{4}(.)\.[^\.] $