Home > Net >  Find string between two characters inside of dict
Find string between two characters inside of dict

Time:11-27

You can I find a substring between characters I want to find this character svm? I looked at Get string between two strings and Find string between two substrings. So this is my string ('svm', SVC()) And I want to find all between ' ' so the result should be svm or dct_test

import re 
dict_SupportVectorMachine = {
    "classifier": ('svm', SVC()),
    "parameters": {'svm__C':[0.001,0.01,0.1,10, 100],
                   'svm__gamma':[0.1,0.01],
                   'svm__kernel':['linear', 'sigmoid']}
}

string = dict_SupportVectorMachine['classifier']
string2 = ('dct_test', ThisCouldbeLongerAndShorter())
subStr = re.findall(r"('(. ?)',",string)
print(subStr)
[OUT]
error: missing ), unterminated subpattern at position 0

CodePudding user response:

It seems that you missed a ) on the fourth line:

import re 
string = "('svm', SVC())"
string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
subStr = re.findall(r"('(. ?))',",string)
print(subStr)

CodePudding user response:

What you have is a tuple of 2 elements : a str and a SVC instance, just get the first index

dict_SupportVectorMachine = {
    "classifier": ('svm', SVC()),
    "parameters": {}
}

classif = dict_SupportVectorMachine['classifier']
print(classif[0])  # svm

OLD answer due to different question

The parenthesis is a special char for building groups, for a real parenthesis yo need to escape it \(. Also use search and not findall here

import re

string = "('svm', SVC())"
print(re.findall(r"\('(. ?)',", string))  # ['svm']
print(re.search(r"\('(. ?)',", string).group(1))  # svm

string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
print(re.findall(r"\('(. ?)',", string2))  # ['dct_test']
print(re.search(r"\('(. ?)',", string2).group(1))  # dct_test
  • Related