-2

I have a list of strings in lst

lst = ["-", "/", ","]

Examples for str to re.sub:

str = "abc - abc 9-4 "   => "abc abc 9-4 " 
str = "abc , abc 9/4 "   => "abc abc 9,4 " 
str = "abc / abc 9,4 "   => "abc abc 9/4 " 

I want to replace all the matches for the given pattern with the string replace_with

I would like to implement it as follows

 new_str = re.sub(pattern,replace_with, str);

where,

replace_with = ""
pattern      =        Please help me define the following in regex

(not number)(anything)(any of the strings in lst) (anything)(not number)

Athul Muralidharan
  • 693
  • 1
  • 10
  • 18
  • [`(?<=\D)\s*[-/,](?=\s*\D)`](https://regex101.com/r/1VFEc2/1) or [`(?<!\d)\s*[-/,](?!\s*\d)`](https://regex101.com/r/1VFEc2/2) according to your specifications. – ctwheels Nov 09 '17 at 18:17
  • Don't complicate things! Seems like all you need is a neg. lookahead: [**`\s*[-,/](?!\d)`**](https://regex101.com/r/WzDvXv/2/) – Jan Nov 09 '17 at 18:17
  • @ctwheels your answer will do the job for me except [-,/] . Because to read this from a list, as the strings I want to check changes in the run time. Can you show how to do that with a list – Athul Muralidharan Nov 09 '17 at 18:48
  • @AthulMuralidharan just use the content from [this](https://stackoverflow.com/questions/280435/escaping-regex-string-in-python) post to escape the joined list. You should have something like `"(?<!\d)\s*[" + re.escape(lst.join()) + "](?!\s*\d)"` (note the actual code I just wrote might not work - I can't test it at the moment - but it will resemble this) – ctwheels Nov 09 '17 at 19:00

1 Answers1

1

You can try this:

lst = ["-", "/", ","]
import re
s = ["abc - abc 9-4 ", "abc , abc 9/4 ", "abc / abc 9,4 "]
final_data = [re.sub('\s|\s'.join(lst), ' ',  i) for i in s]

Output:

['abc  abc 9-4 ', 'abc  abc 9/4 ', 'abc abc 9,4 ']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102