David J.
David J.

Reputation: 1913

match any decimals appearing immediately before a character in python

I can't seem to find an example of this, but I doubt the regex is that sophisticated. Is there a simple way of getting the immediately preceding digits of a certain character in Python? For the character "A" and the string: "&#238A" It should return 238A

Upvotes: 0

Views: 58

Answers (2)

Cheolho Jeon
Cheolho Jeon

Reputation: 471

If you are on python 3, try this. Please refer to this link for more information.

import re
char = "A" # the character you're searching for.
string = "BA &#238A 123A" # test string.
regex = "[0-9]+%s" %char # capturing digits([0-9]) which appear more than once(+) followed by a desired character "%s"%char
compiled_regex = re.compile(regex) # compile the regex
result = compiled_regex.findall(string)
print (result)
>>['238A', '123A']

Upvotes: 0

Steven Doggart
Steven Doggart

Reputation: 43743

As long as you intend to include the trailing character in the resulting match, the regex pattern to do that is very simple. For instance, if you want to capture any series of digits followed by a letter A, the pattern would be \d+A

Upvotes: 1

Related Questions