import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
Answer from CrazyCasta on Stack Overflow
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί library β€Ί re.html
re β€” Regular expression operations β€” Python 3.14.3 ...
1 week ago - The third-party regex module, which has an API compatible with the standard library re module, but offers additional functionality and a more thorough Unicode support. A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).
Discussions

regex - Python: check if string meets specific format - Stack Overflow
Programming in Python3. I am having difficulty in controlling whether a string meets a specific format. So, I know that Python does not have a .contain() method like Java but that we can use rege... More on stackoverflow.com
🌐 stackoverflow.com
String Format Checking in Python - Stack Overflow
While preparing for my AS-Level Computer Science exam I came across a question in the pre-release material: Prompt the user to input a User ID and check if the format of the ID corresponds with pre- More on stackoverflow.com
🌐 stackoverflow.com
python - Check if string has a certain format - Stack Overflow
So not appropriate for the given format. 2019-04-03T03:03:04.657Z+00:00 ... This is definitely a job for regex. A simple regex for that pattern might be ... The "\d" stands for any digit, and the "\." is an escaped period character (because "." is a special symbol in regex.) With python re library would probably use the findall method with that pattern, list_of_matches = re.findall("\d\d\d\.\d\d\d\.\d\d\d", my_string... More on stackoverflow.com
🌐 stackoverflow.com
regex - Python 2.6+ str.format() and regular expressions - Stack Overflow
To match a single backslash in a regex, you need to escape it with another: \\ However that sequence in a non-raw string produces a single backslash but it is not obvious from looking at your regex. In a raw string, your r'\\' comes through as expected. ... you first would need to format string ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com β€Ί python β€Ί python_regex.asp
Python RegEx
Remove List Duplicates Reverse a String Add Two Numbers Β· Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί howto β€Ί regex.html
Regular Expression HOWTO β€” Python 3.14.3 documentation
Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like.
Top answer
1 of 4
5

As for the regex you're looking for I believe that

^bbbb[0-9a-f]{28}$

should validate correctly for your requirements.

As for if there is an easier way than using the re module, I would say that there isn't really to achieve the result you're looking for. While using the in keyword in python works in the way you would expect a contains method to work for a string, you are actually wanting to know if a string is in a correct format. As such the best solution, as it is relatively simple, is to use a regular expression, and thus use the re module.

2 of 4
2

In fact, Python does have an equivalent to the .contains() method. You can use the in operator:

if 'substring' in long_string:
    return True

A similar question has already been answered here.

For your case, however, I'd still stick with regex as you're indeed trying to evaluate a certain String format. To ensure that your string only has hexadecimal values, i.e. 0-9 and a-f, the following regex should do it: ^[a-fA-F0-9]+$. The additional "complication" are the four 'b' at the start of your string. I think an easy fix would be to include them as follows: ^(bbbb)?[a-fA-F0-9]+$.

>>> import re
>>> pattern = re.compile('^(bbbb)?[a-fA-F0-9]+$')
>>> test_1 = 'bbbb00000000000000170d0000306fb6'
>>> test_2 = 'bbbb00000000000000170d0000306fx6'
>>> pattern.match(test_1)
<_sre.SRE_Match object; span=(0, 32), match='bbbb00000000000000170d0000306fb6'>
>>> pattern.match(test_2)
>>>

The part that is currently missing is checking for the exact length of the string for which you could either use the string length method or extend the regex -- but I'm sure you can take it from here :-)

🌐
Python Data Science Handbook
jakevdp.github.io β€Ί WhirlwindTourOfPython β€Ί 14-strings-and-regular-expressions.html
String Manipulation and Regular Expressions | A Whirlwind Tour of Python
The methods of Python's str type give you a powerful set of tools for formatting, splitting, and manipulating string data. But even more powerful tools are available in Python's built-in regular expression module. Regular expressions are a huge topic; there are there are entire books written on the topic (including Jeffrey E.F.
🌐
Delft Stack
delftstack.com β€Ί home β€Ί howto β€Ί python β€Ί python check if string matches regex
How to Check if String Matches Regex in Python | Delft Stack
March 4, 2025 - The re.fullmatch() function checks if the entire string β€œexample@example.com” fits this pattern. Since it does, the function returns a match object, confirming that the email is valid.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί how-to-check-a-valid-regex-string-using-python
How to check a valid regex string using Python? - GeeksforGeeks
July 31, 2023 - Then we assigned a string containing the regex pattern to the variable pattern. The pattern provided is invalid as it contains an unclosed character class (in regex square brackets `[ ]`are used for defining a character class). We placed the re.compile() (used to compile regex patterns) function within the try block. This will firstly try to compile the pattern and if any exception occurs during the compilation, it would firstly check whether it is re.error, if it is then only the except block will execute.
🌐
TutorialsPoint
tutorialspoint.com β€Ί python-check-if-a-string-matches-regex-list
Python - Check if a string matches regex list
August 2, 2023 - Python offers two different primitive operations based on regular expressions, match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).
🌐
QA Touch
qatouch.com β€Ί home β€Ί python regex testing: a comprehensive guide with examples
Python Regex Testing: A Comprehensive Guide with Examples
June 24, 2025 - Step 1: Import the re Module To use regex in Python, you need to import the built-in re module: Step 2: Define the Regex Pattern Identify the pattern you want to match or search for within a string. Regular expressions are written as strings, so define your regex pattern accordingly. ... Step 3: Choose the Appropriate Function Depending on your objective, choose the appropriate re function to match, search, or replace patterns in the text. re.match(): Checks ...
🌐
Ruan Bekker's Blog
ruan.dev β€Ί blog β€Ί 2019 β€Ί 02 β€Ί 27 β€Ί how-to-validate-strings-in-python-with-regex
How to Validate Strings in Python with Regex | Ruan Bekker's Blog
February 27, 2019 - regex = re.compile('my-random-[a-z]{3}-string_[0-9a-z]{32}\Z', re.I) ... match = regex.match(str(input_string)) ... return bool(match) ... >>> mystring = generate_string() >>> mystring 'my-random-ngt-string_6346145281738193742120539836241' >>> validate = validation_check(mystring) >>> if validate == True: ... print('The string {} is valid'.format(mystring)) ...
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί how to use f-string inside regex pattern?
r/learnpython on Reddit: How to use f-string inside Regex Pattern?
March 22, 2022 -

Hello all, this be my code:

zipCode = "AA 45522"
myPat1 = "(\d{1,9})([^,]+?)AA 45522" # the pattern i want

# now interpolating variable name into the regex pattern
myPat2 = f"(\d{1,9})([^,]+?){zipCode}" 
myPat3 = rf"(\d{1,9})([^,]+?){zipCode}" #trying raw 
myPat4 = "(\d{1,9})([^,]+?)"+zipCode

# Results I see in debugger:

myPat1 = '(\\d{1,9})([^,]+?)AA 45522' # correct
myPat4 = '(\\d{1,9})([^,]+?)AA 45522' # correct 
myPat2 = '(\\d(1, 9))([^,]+?)AA 45522' # faulty
myPat3 = '(\\d(1, 9))([^,]+?)AA 45522' # faulty

myPat2 & myPat3 are adding a space between (1, & 9) which is resulting into creation of faulty pattern (which in turn fails to find pattern in my rawString). So why does using f-string inside regex pattern fudge things up? I recall facing same problem few weeks back.

Finally I have to use myPat4 style of coding to make it work, but I love f-strings and want to find a proper solution to using f-strings inside regex pattern. Thanks.

🌐
Spsstools
spsstools.net β€Ί en β€Ί python β€Ί python-index β€Ί strings-python β€Ί validate-content-format-string-variable
Validate Content Format in a String Variable | Raynald's SPSS Tools
This code sample shows how to test if a string corresponds to predefined format (example with SSN and chemical element name). Python re module used for regular expressions.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python-check-if-string-matches-regex-list
Python | Check if string matches regex list | GeeksforGeeks
April 23, 2023 - In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list. ... # Python3 code to demonstrate working of # Check if string matches ...
Top answer
1 of 2
4

You can do it without using regex. Python has strptime() method which parses a string representing a time according to a format. If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.

Here is the code:

import time

given_time = "10:30:45"
try:
    time.strptime(given_time, '%H:%M:%S')
    print("Correct Format")
except ValueError:
    print("Incorrect Format")

Here are its formats:

  • %a - abbreviated weekday name

  • %A - full weekday name

  • %b - abbreviated month name

  • %B - full month name

  • %c - preferred date and time representation

  • %C - century number (the year divided by 100, range 00 to 99)

  • %d - day of the month (01 to 31)

  • %D - same as %m/%d/%y

  • %e - day of the month (1 to 31)

  • %g - like %G, but without the century

  • %G - 4-digit year corresponding to the ISO week number (see %V).

  • %h - same as %b

  • %H - hour, using a 24-hour clock (00 to 23)

  • %I - hour, using a 12-hour clock (01 to 12)

  • %j - day of the year (001 to 366)

  • %m - month (01 to 12)

  • %M - minute

  • %n - newline character

  • %p - either am or pm according to the given time value

  • %r - time in a.m. and p.m. notation

  • %R - time in 24 hour notation

  • %S - second

  • %t - tab character

  • %T - current time, equal to %H:%M:%S

  • %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1

  • %U - week number of the current year, starting with the first Sunday as the first day of the first week

  • %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week

  • %W - week number of the current year, starting with the first Monday as the first day of the first week

  • %w - day of the week as a decimal, Sunday=0

  • %x - preferred date representation without the time

  • %X - preferred time representation without the date

  • %y - year without a century (range 00 to 99)

  • %Y - year including the century

  • %Z or %z - time zone or name or abbreviation

  • %% - a literal % character

2 of 2
2

You can use regex to match the format, then take action depending on if a match is found. Provide re.match() with a pattern and the string you want to check:

import re

strings = ["8:30:00", "16:00:00", "845:00", "aa:bb:00"]

for s in strings:
    if re.match("\d{1,2}:\d{2}:\d{2}", s):  # Will return True if pattern matches s
        print("match: {}".format(s))  # Take action on a matching pattern
    else:
        print("no match: {}".format(s))

The pattern \d{1,2}:\d{2}:\d{2} will match 1 or 2 digits, colon, 2 digits, colon, and 2 digits

The above will print:

match: 8:30:00
match: 16:00:00
no match: 845:00
no match: aa:bb:00
🌐
Google
developers.google.com β€Ί google for education β€Ί python β€Ί python regular expressions
Python Regular Expressions | Python Education | Google for Developers
\d -- decimal digit [0-9] (some older regex utilities do not support \d, but they all support \w and \s) ^ = start, $ = end -- match the start or end of the string Β· \ -- inhibit the "specialness" of a character. So, for example, use \. to match a period or \\ to match a slash. If you are unsure if a character has special meaning, such as '@', you can try putting a slash in front of it, \@. If its not a valid escape sequence, like \c, your python program will halt with an error.