Programming

두 개의 하위 문자열 사이에서 문자열 찾기

procodes 2020. 5. 10. 11:52
반응형

두 개의 하위 문자열 사이에서 문자열 찾기


이 질문에는 이미 답변이 있습니다.

두 개의 하위 문자열 (

'123STRINGabc' -> 'STRING'

) 사이에 문자열을 찾으려면 어떻게합니까 ?내 현재 방법은 다음과 같습니다

>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis

그러나 이것은 매우 비효율적이고 비 유적으로 보입니다. 이와 같은 작업을 수행하는 더 좋은 방법은 무엇입니까?문자열은 시작과 끝되지 않을 수 있습니다 언급하는 것을 잊었다

start

하고

end

. 전후에 더 많은 문자가있을 수 있습니다.


import re

s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))

s = "123123STRINGabcabc"

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

def find_between_r( s, first, last ):
    try:
        start = s.rindex( first ) + len( first )
        end = s.rindex( last, start )
        return s[start:end]
    except ValueError:
        return ""


print find_between( s, "123", "abc" )
print find_between_r( s, "123", "abc" )

제공합니다 :

123STRING
STRINGabc

내가 주목해야 생각 - 당신이, 당신은 혼합 할 수 있습니다 필요한 행동을 따라

index

하고

rindex

전화를 걸거나 위의 버전 중 하나에 가서 (이 정규식의 동등 물

(.*)

(.*?)

그룹).


start = 'asdf=5;'
end = '123jasd'
s = 'asdf=5;iwantthis123jasd'
print s[s.find(start)+len(start):s.rfind(end)]

준다

iwantthis

s[len(start):-len(end)]

문자열 형식은 Nikolaus Gradwohl이 제안한 것에 약간의 유연성을 추가합니다.

start

그리고

end

원하는대로 지금 수정 될 수 있습니다.

import re

s = 'asdf=5;iwantthis123jasd'
start = 'asdf=5;'
end = '123jasd'

result = re.search('%s(.*)%s' % (start, end), s).group(1)
print(result)

OP의 자체 솔루션을 답변으로 변환하면됩니다.

def find_between(s, start, end):
  return (s.split(start))[1].split(end)[0]

여기에 한 가지 방법이 있습니다

_,_,rest = s.partition(start)
result,_,_ = rest.partition(end)
print result

정규 표현식을 사용하는 다른 방법

import re
print re.findall(re.escape(start)+"(.*)"+re.escape(end),s)[0]

또는

print re.search(re.escape(start)+"(.*)"+re.escape(end),s).group(1)

source='your token _here0@df and maybe _here1@df or maybe _here2@df'
start_sep='_'
end_sep='@df'
result=[]
tmp=source.split(start_sep)
for par in tmp:
  if end_sep in par:
    result.append(par.split(end_sep)[0])

print result

여기에 표시해야합니다 : here0, here1, here2정규식이 더 좋지만 추가 lib가 필요합니다. 파이썬에만 가고 싶을 수도 있습니다.


아무것도 가져 오지 않으려면 문자열 방법을 시도하십시오

.index()

.

text = 'I want to find a string between two substrings'
left = 'find a '
right = 'between two'

# Output: 'string'
print text[text.index(left)+len(left):text.index(right)]

를 추출하려면 다음을

STRING

시도하십시오.

myString = '123STRINGabc'
startString = '123'
endString = 'abc'

mySubString=myString[myString.find(startString)+len(startString):myString.find(endString)]

이 솔루션은 시작 문자열과 최종 문자열이 다르다고 가정합니다. readlines ()를 사용하여 전체 파일을 읽었다 고 가정 할 때 초기 및 최종 표시기가 동일 할 때 전체 파일에 사용하는 솔루션은 다음과 같습니다.

def extractstring(line,flag='$'):
    if flag in line: # $ is the flag
        dex1=line.index(flag)
        subline=line[dex1+1:-1] #leave out flag (+1) to end of line
        dex2=subline.index(flag)
        string=subline[0:dex2].strip() #does not include last flag, strip whitespace
    return(string)

예:

lines=['asdf 1qr3 qtqay 45q at $A NEWT?$ asdfa afeasd',
    'afafoaltat $I GOT BETTER!$ derpity derp derp']
for line in lines:
    string=extractstring(line,flag='$')
    print(string)

제공합니다 :

A NEWT?
I GOT BETTER!

이 코드를 사용하거나 아래 함수를 복사하면됩니다. 한 줄에 깔끔하게 정리되어 있습니다.

def substring(whole, sub1, sub2):
    return whole[whole.index(sub1) : whole.index(sub2)]

다음과 같이 기능을 실행하면

print(substring("5+(5*2)+2", "(", "("))

아마 출력이 남을 것입니다 :

(5*2

오히려

5*2

출력 끝에 하위 문자열을 포함 시키려면 코드는 다음과 같아야합니다.

return whole[whole.index(sub1) : whole.index(sub2) + 1]

그러나 마지막에 하위 문자열을 원하지 않으면 +1이 첫 번째 값에 있어야합니다.

return whole[whole.index(sub1) + 1 : whole.index(sub2)]

다음은 string1과 string2 사이에 문자열이 검색 된 목록을 반환하는 함수입니다.

def GetListOfSubstrings(stringSubject,string1,string2):
    MyList = []
    intstart=0
    strlength=len(stringSubject)
    continueloop = 1

    while(intstart < strlength and continueloop == 1):
        intindex1=stringSubject.find(string1,intstart)
        if(intindex1 != -1): #The substring was found, lets proceed
            intindex1 = intindex1+len(string1)
            intindex2 = stringSubject.find(string2,intindex1)
            if(intindex2 != -1):
                subsequence=stringSubject[intindex1:intindex2]
                MyList.append(subsequence)
                intstart=intindex2+len(string2)
            else:
                continueloop=0
        else:
            continueloop=0
    return MyList


#Usage Example
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y68")
for x in range(0, len(List)):
               print(List[x])
output:


mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","3")
for x in range(0, len(List)):
              print(List[x])
output:
    2
    2
    2
    2

mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y")
for x in range(0, len(List)):
               print(List[x])
output:
23
23o123pp123

내 방법은 다음과 같은 일을하는 것입니다.

find index of start string in s => i
find index of end string in s => j

substring = substring(i+len(start) to j-1)

이것은 본질적으로 cji의 답변입니다-Jul 30 '10 at 5:58. 예외를 일으킨 원인을 좀 더 명확하게하기 위해 시도 제외 구조를 변경했습니다.

def find_between( inputStr, firstSubstr, lastSubstr ):
'''
find between firstSubstr and lastSubstr in inputStr  STARTING FROM THE LEFT
    http://stackoverflow.com/questions/3368969/find-string-between-two-substrings
        above also has a func that does this FROM THE RIGHT   
'''
start, end = (-1,-1)
try:
    start = inputStr.index( firstSubstr ) + len( firstSubstr )
except ValueError:
    print '    ValueError: ',
    print "firstSubstr=%s  -  "%( firstSubstr ), 
    print sys.exc_info()[1]

try:
    end = inputStr.index( lastSubstr, start )       
except ValueError:
    print '    ValueError: ',
    print "lastSubstr=%s  -  "%( lastSubstr ), 
    print sys.exc_info()[1]

return inputStr[start:end]    

이것은 전에

Daniweb에서 코드 스 니펫

으로 게시 했습니다 .

# picking up piece of string between separators
# function using partition, like partition, but drops the separators
def between(left,right,s):
    before,_,a = s.partition(left)
    a,_,after = a.partition(right)
    return before,a,after

s = "bla bla blaa <a>data</a> lsdjfasdjöf (important notice) 'Daniweb forum' tcha tcha tchaa"
print between('<a>','</a>',s)
print between('(',')',s)
print between("'","'",s)

""" Output:
('bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f (important notice) 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f (important notice) ', 'Daniweb forum', ' tcha tcha tchaa')
"""

from timeit import timeit
from re import search, DOTALL


def partition_find(string, start, end):
    return string.partition(start)[2].rpartition(end)[0]


def re_find(string, start, end):
    # applying re.escape to start and end would be safer
    return search(start + '(.*)' + end, string, DOTALL).group(1)


def index_find(string, start, end):
    return string[string.find(start) + len(start):string.rfind(end)]


# The wikitext of "Alan Turing law" article form English Wikipeida
# https://en.wikipedia.org/w/index.php?title=Alan_Turing_law&action=edit&oldid=763725886
string = """..."""
start = '==Proposals=='
end = '==Rival bills=='

assert index_find(string, start, end) \
       == partition_find(string, start, end) \
       == re_find(string, start, end)

print('index_find', timeit(
    'index_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

print('partition_find', timeit(
    'partition_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

print('re_find', timeit(
    're_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

결과:

index_find 0.35047444528454114
partition_find 0.5327825636197754
re_find 7.552149639286381

re_find

 

index_find

이 예제 보다 거의 20 배 느 렸습니다 .


Parsing text with delimiters from different email platforms posed a larger-sized version of this problem. They generally have a START and a STOP. Delimiter characters for wildcards kept choking regex. The problem with split is mentioned here & elsewhere - oops, delimiter character gone. It occurred to me to use replace() to give split() something else to consume. Chunk of code:

nuke = '~~~'
start = '|*'
stop = '*|'
julien = (textIn.replace(start,nuke + start).replace(stop,stop + nuke).split(nuke))
keep = [chunk for chunk in julien if start in chunk and stop in chunk]
logging.info('keep: %s',keep)

Further from Nikolaus Gradwohl answer, I needed to get version number (i.e., 0.0.2) between('ui:' and '-') from below file content (filename: docker-compose.yml):

    version: '3.1'
services:
  ui:
    image: repo-pkg.dev.io:21/website/ui:0.0.2-QA1
    #network_mode: host
    ports:
      - 443:9999
    ulimits:
      nofile:test

and this is how it worked for me (python script):

import re, sys

f = open('docker-compose.yml', 'r')
lines = f.read()
result = re.search('ui:(.*)-', lines)
print result.group(1)


Result:
0.0.2

This seems much more straight forward to me:

import re

s = 'asdf=5;iwantthis123jasd'
x= re.search('iwantthis',s)
print(s[x.start():x.end()])

참고URL : https://stackoverflow.com/questions/3368969/find-string-between-two-substrings

반응형