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
'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
Reply
#2
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
guddu_12 likes this post
Reply
#3
It is working fine

Thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Color a table cell based on specific text Creepy 11 1,947 Jul-27-2023, 02:48 PM
Last Post: deanhystad
  extract only text strip byte array Pir8Radio 7 2,909 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
  Extract only certain text which are needed Calli 26 5,818 Oct-10-2022, 03:58 PM
Last Post: deanhystad
  Extract text rektcol 6 1,668 Jun-28-2022, 08:57 AM
Last Post: Gribouillis
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,505 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Extracting Specific Lines from text file based on content. jokerfmj 8 2,943 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Extract a string between 2 words from a text file OscarBoots 2 1,862 Nov-02-2021, 08:50 AM
Last Post: ibreeden
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 4,378 Aug-13-2021, 08:21 PM
Last Post: Winfried
  regex pattern to extract relevant sentences Bubly 2 1,861 Jul-06-2021, 04:17 PM
Last Post: Bubly
  Extract specific sentences from text file Bubly 3 3,390 May-31-2021, 06:55 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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