Python Forum
How to catch string between two strings
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to catch string between two strings
#1
Hi,

I have below code to catch a string between two strings using a code as below:

I want to catch a string between '.csv' & _ just before .csv. Desired output is: JCET01, but using below code is giving the out I desired.

import re

filename='input_file_JCET01.csv'

result = re.search('_(.*).csv', filename)
Reply
#2
#! /usr/bin/python3
import re
filename='input_file_JCET01.csv'
result = re.search('file_(.*).csv', filename)
print(result.group(1))
Reply
#3
Another way, without re:

>>> filename.rsplit('_', maxsplit=1)      # split on underscore from right one time                                     
['input_file', 'JCET01.csv']
>>> filename.rsplit('_', maxsplit=1)[1]   # select second element                                    
>>> 'JCET01.csv'
>>> filename.rsplit('_', maxsplit=1)[1].split('.')     # split element on period                     
['JCET01', 'csv']
>>> filename.rsplit('_', maxsplit=1)[1].split('.')[0]  # select first element                  
'JCET01'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
The solution of perfrigon is easier to understand.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Regex to catch what user has put in text box robertkwild 26 5,180 Jun-26-2024, 01:06 PM
Last Post: AdamHensley
  Trying to understand strings and lists of strings Konstantin23 2 1,797 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  try catch not working? korenron 2 1,571 Jan-15-2023, 01:54 PM
Last Post: korenron
  Multiprocessing queue catch get timeout Pythocodras 1 4,411 Apr-22-2022, 06:01 PM
Last Post: Pythocodras
  Splitting strings in list of strings jesse68 3 2,594 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Search multiple CSV files for a string or strings cubangt 7 13,245 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  twisted: catch return from sql wardancer84 0 1,929 Sep-08-2021, 12:38 PM
Last Post: wardancer84
  how to catch schema error? maiya 0 2,574 Jul-16-2021, 08:37 AM
Last Post: maiya
  is this a good way to catch exceptions? korenron 14 7,126 Jul-05-2021, 06:20 PM
Last Post: hussaind
  pool mysql error - not catch by try\except? korenron 1 2,888 Jul-05-2021, 11:26 AM
Last Post: ibreeden

Forum Jump:

User Panel Messages

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