Mike
Mike

Reputation: 637

python 2.7 regex search at pos where '^' starts at pos

This may have been asked already but I can't seem to find any duplicates so I am going to ask myself and hope I don't get flagged.

I am building a small parser using a state machine that switches into a sub-parser whenever a { is detected. I only want the very first occurrence of what my regex will match at the position I am currently at. Basically my regex is keymatch = re.compile(r'^\{([A-Za-z0-9])\}') and I am using the string this {is} a {test} string.

The problem is I am getting no match when I run keymatch.match(myString, pos) I have also tried with keymatch.search(myString, pos) and found the same result.

For the record, pos is pointing at the correct location, hard coded values also return none, while no position or leading ^ in my regex returns all the matches, which I do not want because of how I am rebuilding the string character by character. In addition, if a match is not found at pos, I want my match object to be none to trigger an error rather than just give me anything down the string it finds.

Is anything noticeably wrong with my approach, and if so, what can I do to fix it?

Upvotes: 0

Views: 50

Answers (1)

Gerhard Powell
Gerhard Powell

Reputation: 6175

^ is indicating the beginning of the string. So it is only searching for the first character being an open bracket. You can remove the ^

Upvotes: 1

Related Questions