Skitzafreak
Skitzafreak

Reputation: 1917

Regex not matching values

So I am creating a program which reads input Strings, and sees if they contains codes within a list. I am attempting to use a regex to get the matching string, but am having a bit of a problem with my regex. Here is my code for reference:

import re

values = ["T1245F8", "T1267F8", "T1234F8"]

checkVals = ["rfgT12B45F8asd", "b65dT12B67F8lgkt", "4fgy7tgT12B34F8", "fgtrfT12B94F8fkg"]

for i in range(len(checkVals)):
    match = False
    parsedVal = re.match('T12B[0-9]{2}F8', checkVals[i])
    for j in range(len(values)):
        if parsedVal == values[j]:
            match = True
    print(match)

The output I am expecting if 3 True and 1 False statement printed out. However instead of get 4 False statements.

EDIT: Fixed a typo in my regex, but it still isn't working.

Upvotes: 0

Views: 641

Answers (3)

Rayhane Mama
Rayhane Mama

Reputation: 2424

It may be just a typo in your question post but i think you meant:

values = ["T12B45F8", "T12B67F8", "T12B34F8"]

then, just change this line:

parsedVal = re.match('T12B[0-9]{2}F8', checkVals[i])

to this one:

parsedVal = re.search('T12B[0-9]{2}F8', checkVals[i]).group()

this will give you the actual parts you're matching.

output:

True
True
True
False

as a conclusion, the entire code should look like this:

import re

values = ["T12B45F8", "T12B67F8", "T12B34F8"]

checkVals = ["rfgT12B45F8asd", "b65dT12B67F8lgkt", "4fgy7tgT12B34F8", "fgtrfT12B94F8fkg"]

for i in range(len(checkVals)):
    match = False
    parsedVal = re.search('T12B[0-9]{2}F8', checkVals[i]).group()
    for j in range(len(values)):
        if parsedVal == values[j]:
            match = True
    print(match)

I believe this is what you're looking for.

Upvotes: 2

Tony
Tony

Reputation: 3068

I think there is 2 problems

First:

The $ at the end of the regex is not allowing any characters after

Second:

Should be searching for T12B not T12

*It is also possible you made a type while entering your test data. For example rfgT12B45F8asd will not match your current expression because it contains T12B as a prefix to your numbers not T12

Final Regex:

T12B[0-9]{2}F8

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

Remove $ from your regexp, it matches at the end of string, while your strings don't end in F8. Also, use re.search instead of re.match.

Upvotes: -1

Related Questions