0

I'm trying to create pattern that detects certain strings. Basically, the purpose is if detect 'ABCDEF' in a string then return "true". but between 'ABC' and 'DEF', there would be (L+count) or (number) or not like examples below. BTW all examples below return "true". It would be really appreciate if some one can advise how to ignore those combo of number and characters between "ABC" and "DEF"?

 ABC(L30)(345)DEF, ABC(L2)(45)DEF, ABCDEF, ABC(L10)DEF, ABC(2)DEF 

2 Answers 2

1

Regex compose thinking path:

  • Start with ABC
  • Ends with DEF
  • Either (L[0-9]+) or ([0-9]+) or empty
#!/usr/bin/python import re r=re.compile("ABC(\(L[0-9]+\)|\([0-9]+\)|)*DEF"); lines = [ "ABC(L30)(345)DEF", "ABC(L2)(45)DEF", "ABC(L30)DEF", "ABC(345)DEF", "ABCDEF", "ABCxyzDEF", "ABC(L)DEF", "ABC(A)DEF", "ABC()DEF", ] for str in lines: if r.match(str): print " match : %s" % str else: print "not match : %s" % str 

Output:

 match : ABC(L30)(345)DEF match : ABC(L2)(45)DEF match : ABC(L30)DEF match : ABC(345)DEF match : ABCDEF not match : ABCxyzDEF not match : ABC(L)DEF not match : ABC(A)DEF not match : ABC()DEF 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you Ken, this is the solution what I was looking for!
0
def is_in(string_,word_): import re return word_ in [''.join(re.split('\(.+?\)\(.+?\)|\(.+?\)',string_))][0] s = "ABC(L30)(345)DEF, ABC(L2)(45)DEF, ABCDEF, ABC(L10)DEF, ABC(2)DEF" print(is_in(s,'ABCDEF')) True 

1 Comment

I revised the question. the purpose is to return "true" if it detects "ABCDEF" in a string. and all above 5 cases shows different cases that returns "True".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.