Python Forum
Extract text based on postion and pattern
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extract text based on postion and pattern
#1
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
'[email protected]@[email protected]@ghee @@ 3 ghee
'[email protected]@[email protected]@ghee @@ -3 but

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

Can any one guide me
Reply
#2
Looks like you could just feed the separator and the pattern to split().

search_info = """'inf***maint***three' *** 2
'[email protected]@[email protected]@ghee @@ 3
'[email protected]@[email protected]@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 [email protected]@[email protected]@ghee is -> ghee The -3 item from [email protected]@[email protected]@ghee is -> but
guddu_12 likes this post
Reply
#3
It is working fine

Thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Extract text rektcol 6 540 Jun-28-2022, 08:57 AM
Last Post: Gribouillis
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 668 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Extracting Specific Lines from text file based on content. jokerfmj 8 1,031 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Extract a string between 2 words from a text file OscarBoots 2 1,008 Nov-02-2021, 08:50 AM
Last Post: ibreeden
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 1,943 Aug-13-2021, 08:21 PM
Last Post: Winfried
  regex pattern to extract relevant sentences Bubly 2 1,166 Jul-06-2021, 04:17 PM
Last Post: Bubly
  Extract specific sentences from text file Bubly 3 1,816 May-31-2021, 06:55 PM
Last Post: Larz60+
  extract color text from PDF Maha 0 1,238 May-31-2021, 04:05 PM
Last Post: Maha
  A text-based game [SOLVED] Gameri1 6 2,550 Apr-20-2021, 02:26 PM
Last Post: buran
Question How to extract multiple text from a string? chatguy 2 1,505 Feb-28-2021, 07:39 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020