0

I would like to test a string:

BASE[A-Z] + SINGLE CHAR {F,G,H,J,K,M,N,Q,U,V,X,Z} + SINGLE NUMERIC [0-9]

The 'BASE' is at least one character long.

eg. 'ESZ6' -> True, 'ESSP6' -> False

I appreciate I can do:

import re
prog = re.compile('[A-Z]+[FGHJKMNQUVXZ]{1}[\d]{1}')

...

if prog.search(string):
    print('This matched...')

I then wanted to use:

matches = [i for i in items if prog.search(item)]

Is this the optimal way of implementing this?

1
  • 1
    prog = re.compile(r'^[A-Z]+[FGHJKMNQUVXZ]\d$') Commented Jan 15, 2016 at 18:01

1 Answer 1

1

This depends on what you mean by, 'test a string'. Do you want to check if the entire string matches your pattern, or if the pattern just happens to occur in your string, e.g. 'ESZ6' vs. "I've got an ESZ6 burning a hole in my pocket'. Can other characters abut your target, eg. '123ESZ6ARE'?

Assuming we're just testing individual tokens like 'ESZ6' and 'ESSP6', then here are some code ideas:

import re

items = ('ESZ6', 'ESSP6')

prog = re.compile(r"[A-Z]+[FGHJKMNQUVXZ]\d$")

matches = [item for item in items if prog.match(item)]

Use .match() instead of .search() unless you want an unanchored search. Drop the final '$' if you want the end unanchored. (If using Python 3.4 or later, and want an anchored search, you can probably drop the '$' and use .fullmatch instead of .match)

Pattern match operators only match one character sans repetition operators so you don't need the {1} indications. Use raw strings, r"\d", when dealing with patterns to keep Python from messing with your back slashes.

Your description and your examples don't match exactly so I'm making some assumptions here.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, for the last line look at filter(function, iterable), this is built into python. full detail here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.