Python Forum
Extract text based on postion and pattern - 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: Extract text based on postion and pattern (/thread-35079.html)



Extract text based on postion and pattern - guddu_12 - Sep-27-2021

Hello Gurus,

I am from sql background and i am working on one python requirement to extract text from the give string based on position and pattern.

For e.g

input search_pattern position expected_output
'inf***maint***three' *** 2 maint
'but@@milk@@ghee @@ 3 ghee
'but@@milk@@ghee @@ -3 but

Have tried above using substring and instr in sql but very leangth code.

Can any one guide me


RE: Extract text based on postion and pattern - bowlofred - Sep-27-2021

Looks like you could just feed the separator and the pattern to split().

search_info = """'inf***maint***three' *** 2
'but@@milk@@ghee @@ 3
'but@@milk@@ghee @@ -3"""

for line in search_info.splitlines():
    pattern, separator, position = line.split()
    pattern = pattern.strip("'").rstrip("'")
    index = int(position)
    if index < 0:
        index += 1
    item = pattern.split(separator)[index-1]
    print(f"The {position} item from {pattern} is -> {item}")
Output:
The 2 item from inf***maint***three is -> maint The 3 item from but@@milk@@ghee is -> ghee The -3 item from but@@milk@@ghee is -> but



RE: Extract text based on postion and pattern - guddu_12 - Sep-27-2021

It is working fine

Thank you