Alex Rivera | Logout

Regular expression for hexadecimal string in python not working

Asked 2012-04-22T17:43:10.987
9

I have a regular expression to match strings like:

--D2CBA65440D

--77094A27E09

--77094A27E

--770

--77094A27E09--

basically, it matches a hexadecimal string surrounded by one or more line breaks or white space, and has the prefix -- and may or may not have -- as suffix

i use the following python code, and it works fine most of the time:

hexaPattern = "\s--[0-9a-fA-F]+[--]?\s"
hex = re.search(hexaPattern, part)
if hex:
   print "found a match"

this works for all of the above but it doesn't match --77094A27E09 in this block:

<div id="arrow2" class="headerLinksImg" style="display:block

--77094A27E09

;">

but matches the same string in:

<input type="checkbox" name="checkbox" id="checkboxKG3" class

--77094A27E09

Content-T="checkboxKG" value="KG3" />

What am i doing wrong?

Edit
Report

1 Answer

4

Try this: hexaPattern = r"^--[0-9a-fA-F]+(--)?\s"

The fixes I inserted are:

r at the beginning, so that that backslashes won't be "eaten" by the quotation marks

^ at the beginning to match the start of the string

then -- in parenthesis instead of square brackets (the brackets seem like a mistake)

answered 2012-04-22T17:49:28.833

Your Answer