-1

I need to find a pattern in a string.

The pattern is multi line, and contain only ASCII chars:

p = """
_o_
 |
/ \
"""

And in this string I have to count the pattern(also can contain all ASCII char):

search_text = """
             _o_
              |
             / \               _o_
_o_                             |        _o_      
 |                             / \        |
/ \                                        \  <= this guy is not valid
"""

Question: Should I use regex, or some other algorithm?

Peter
  • 1,019
  • 5
  • 12
  • If you dont konw the width of a string I dont think you can use regex here, I think you'll have to use a standard search alogrithm – Mitch Mar 26 '20 at 20:39
  • thanx for answer, can You recommend some search algorithm for it maybe? (If there is some) – Peter Mar 26 '20 at 20:50
  • Well @Peter, I was about to answer your question with an algorithm besides regex. So if you can make it with regex, try to get the question reopen by editing it with relevant information that make it not a duplicate, only then I would be able to post my answer. Don't know if the algorithm would be better than regex, but just a different approach. Good Luck – DarK_FirefoX Mar 26 '20 at 23:13

1 Answers1

-2

Possibly...

import re

pattern = r"(o)"

# patterns in a multiline string
search_text = """
             _o_
              |
             / \               _o_
_o_                             |
 |                             / \
/ \ 
"""

print('Number of heads found: ' + str(len(re.findall(pattern, search_text, flags=re.MULTILINE))))

Outputs:

Number of heads found: 3

If 'heads' doesn't work maybe something else that appears in all of the groups of patterns? Just a thought.

MDR
  • 619
  • 5
  • 9
  • Thanx for answer, but in the test case also can appear all ASCII char. Will update the question – Peter Mar 26 '20 at 21:38