recompile issues - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: recompile issues (/thread-11325.html) |
recompile issues - 3Pinter - Jul-03-2018 Hi guys, Trying to a simple match with a variable input. * list1['30 dfa00','NOPE 223123','41 53452','XX 123453','342'] * variable ...could be anything. Basicly it should do something like: if list1 starts with variable: remove those characters, return the rest of the string else return full string. import re # the variable is ALWAYS [number][number][space] # prog = re.compile('(0-9)+( )') list1=['30 dfa00','NOPE 223123','41 53452','XX 123453','342'] output=[] for l in list1: if prog.match(l): output.append(l.split(3)[1]) else: output.append(l) print(output) #should return #dfa00, NOPE 223123, 53452, XX 123453, 342What am I doing wrong? import re # the variable is ALWAYS [number][number][space] # prog = re.compile("([0-9]+)+( )") list1=['30 dfa00','NOPE 223123','41 53452','XX 123453','342'] output=[] for l in list1: if prog.match(l): output.append(l.split(3:)) else: output.append(l) print(output) #should return #dfa00, NOPE 223123, 53452, XX 123453, 342Hmmm this is what I have now ... and it seems to work. Good approach? RE: recompile issues - gontajones - Jul-03-2018 prog = re.compile("[0-9]+ ")And for just two numbers: prog = re.compile("[0-9]{2} ") RE: recompile issues - 3Pinter - Jul-03-2018 (Jul-03-2018, 03:34 PM)gontajones Wrote:prog = re.compile("[0-9]+ ")And for just two numbers: @gontajones, thanks for your feedback! Learned something from it. Just for my understanding... Since I'm trying to do something with the first characters of a string (and only those) ... I read that using the "^" triggers the beginning of the string (and neglecting the rest). If a string would be "sometextandnumbers 44 otherthingstoo" to my understanding my current re.compile should return 'etextandnumbers 44 otherthingstoo' .... but it doesn't (returns full string). So adding the '^' would be unnecessary but feels unnatural. Your 50 cents on this? RE: recompile issues - gontajones - Jul-03-2018 I test all my regex here Regex101. Try it by yourself and you'll learn a lot. ^ = for the start of the regex $ = for the end What is your current re.compile()? What do you want to get from "sometextandnumbers 44 otherthingstoo"? The 44? Just use the " " as limiters. Like ( [0-9]+ ) .
RE: recompile issues - snippsat - Jul-03-2018 Instead of trying to split string after the match,let regex to the whole job with re.sub() .>>> import re >>> >>> list1 = ['30 dfa00','NOPE 223123','41 53452','XX 123453','342'] >>> output = [] >>> for item in list1: ... output.append(re.sub(r'^\d{2}\s', '', item)) ... >>> output ['dfa00', 'NOPE 223123', '53452', 'XX 123453', '342'] RE: recompile issues - 3Pinter - Jul-04-2018 Thanks both for your helpfull insight! |