0

I want to modify the string test, to only have "TEXT" left. Therefor everything after "TEXT" is deleted. I figured that out. But how do I use re.sub to cut everything before "TEXT"? I only want to use " 265" and "159 " as criteria to determine when to delete.

test = "314 159 TEXT 265 357" 
test = re.sub(r' 265.*$', '', test) 
print(test)

The Output should be "TEXT"

F.Ima
  • 13
  • 2
  • What is the expected output? Unclear: *" I only want to use " 265" and "159 " as criteria..."*. – Austin Nov 14 '18 at 18:18
  • Possible duplicate of [Stripping everything but alphanumeric chars from a string in Python](https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python) – l'L'l Nov 14 '18 at 18:19
  • ...`test = ''.join(x for x in test if x.isalpha())`... – l'L'l Nov 14 '18 at 18:21
  • the same way I used ' 265' in re.sub; The Output should be "TEXT" – F.Ima Nov 14 '18 at 18:23
  • Why do you want to do this with `re.sub`? It seems like the wrong tool for the job; `re.search` would be more appropriate. – user2357112 Nov 14 '18 at 18:28
  • the example "TEXT" is dynamic I only now what is behind and before it – F.Ima Nov 14 '18 at 18:32
  • Yeah, I guessed that (which is why I didn't suggest `test = 'TEST'`), but that doesn't change the fact that `re.search` would still be more appropriate than `re.sub`. – user2357112 Nov 14 '18 at 18:35

1 Answers1

0

Use a similar pattern as you did for subbing the end, and string them together.:

test = re.sub(r'.* 159 ', '', re.sub(r' 265.*$', '', test))

Alternatively, you could do it with a single pattern and re.findall:

test = re.findall(r'^.*159 ([A-Z]+) 265.*$', test)
Tim
  • 2,756
  • 1
  • 15
  • 31