Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Failing regex
#1
Greetings!
I'm trying to find strings with a particular word(s).
Here are the words:
BG13TPPVxxxx -- where xxxx are the 4 digits
BG13TPPVxxxx(B or C) -- and the letters "B" or "C" at the end

I got this regex but it is failing, it also picks up words with SPPV.
Like this:
BG13SPPVxxxx

if re.search('^[a-zA-Z]{2}\d{2}TPPV\d{4}\.|[b|C]\.',x) 
Thank you!
Reply
#2
This should work.
>>> import re
>>> 
>>> s = 'BG13TPPV1234B'
>>> r = re.search(r"\w+\d{2}TPPV\d+[BC]", s)
>>> r.group()
'BG13TPPV1234B'
>>> 
>>> s = 'BG13TPPV9999C'
>>> r = re.search(r"\w+\d{2}TPPV\d+[BC]", s)
>>> r.group()
'BG13TPPV9999C'
>>> 
>>> s = 'BG13SPPV1245B'
>>> r = re.search(r"\w+\d{2}TPPV\d+[BC]", s)
>>> r.group()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
tester_V likes this post
Reply
#3
I never thought about it as three different search words!
Let's I'll try it...

Thank you!
Reply
#4
This kind of works.
import re

text = ".BG13TPPV123..BG13TPPV2345...BG13TPPV3456B...BG13TPPV4567C...BG13TPPV7890D"

print(re.findall(r"\w+\d{2}TPPV\d{4}[BC]?", text))
Output:
['BG13TPPV2345', 'BG13TPPV3456B', 'BG13TPPV4567C', 'BG13TPPV7890']
Notice that it matches part of "BG13TPPV7890D" because "BG13TPPV7890" is a match to the pattern.

A stricter match is possible if we are willing to specify the character that follows the string. This pattern says the string must be followed by something that is not normally part of a word (whitespace, punctuation).
import re

text = ".BG13TPPV123..BG13TPPV2345...BG13TPPV3456B...BG13TPPV4567C...BG13TPPV7890D."

print(re.findall(r"(\w+\d{2}TPPV\d{4}[BC]?)\W", text))
Output:
['BG13TPPV2345', 'BG13TPPV3456B', 'BG13TPPV4567C']
tester_V likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Failing to connect by 'net use' tester_V 1 256 Apr-20-2024, 06:31 AM
Last Post: tester_V
  Failing regex, space before and after the "match" tester_V 6 1,268 Mar-06-2023, 03:03 PM
Last Post: deanhystad
  Failing to connect to a host with WMI tester_V 6 4,501 Aug-10-2021, 06:25 PM
Last Post: tester_V
  Failing to get Stat for a Directory tester_V 11 3,669 Jul-20-2021, 10:59 PM
Last Post: Larz60+
  Failing to Zip files tester_V 4 2,229 Dec-01-2020, 07:28 AM
Last Post: tester_V
  Python 3.8 on mac failing to start sgandon 0 2,950 Jan-14-2020, 10:58 AM
Last Post: sgandon
  trying to install oandapy and failing ErnestTBass 0 1,971 Feb-24-2019, 06:13 PM
Last Post: ErnestTBass
  Pyinstaller failing JP_ROMANO 2 4,136 Jan-16-2019, 06:07 PM
Last Post: JP_ROMANO
  Why is my for loop failing? microphone_head 4 3,040 Sep-11-2018, 01:21 PM
Last Post: microphone_head

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020