Sto cercando di utilizzare un'espressione regolare dettagliata in Python (2.7). Se è importante, sto solo cercando di rendere più facile tornare indietro e capire più chiaramente l'espressione in futuro. Poiché sono nuovo, per prima cosa ho creato un'espressione compatta per assicurarmi di ottenere ciò che volevo.Come implementare un REGEX in Python
Ecco l'espressione compatta:
test_verbose_item_pattern = re.compile('\n{1}\b?I[tT][eE][mM]\s+\d{1,2}\.?\(?[a-e]?\)?.*[^0-9]\n{1}')
Funziona come previsto
Qui è l'espressione Verbose
verbose_item_pattern = re.compile("""
\n{1} #begin with a new line allow only one new line character
\b? #allow for a word boundary the ? allows 0 or 1 word boundaries \nITEM or \n ITEM
I # the first word on the line must begin with a capital I
[tT][eE][mM] #then we need one character from each of the three sets this allows for unknown case
\s+ # one or more white spaces this does allow for another \n not sure if I should change it
\d{1,2} # require one or two digits
\.? # there could be 0 or 1 periods after the digits 1. or 1
\(? # there might be 0 or 1 instance of an open paren
[a-e]? # there could be 0 or 1 instance of a letter in the range a-e
\)? # there could be 0 or 1 instance of a closing paren
.* #any number of unknown characters so we can have words and punctuation
[^0-9] # by its placement I am hoping that I am stating that I do not want to allow strings that end with a number and then \n
\n{1} #I want to cut it off at the next newline character
""",re.VERBOSE)
Il problema è che quando faccio funzionare il modello verbose ottengo un eccezione
Traceback (most recent call last):
File "C:/Users/Dropbox/directEDGAR-Code-Examples/NewItemIdentifier.py", line 17, in <module>
""",re.VERBOSE)
File "C:\Python27\lib\re.py", line 190, in compile
return _compile(pattern, flags)
File "C:\Python27\lib\re.py", line 242, in _compile
raise error, v # invalid expression
error: nothing to repeat
Ho paura che questo sia qualcosa di sciocco ma non riesco a capirlo. Ho preso le mie espressioni prolisse e l'ho compattato riga per riga per assicurarmi che la versione compatta fosse la stessa del verboso.
Il messaggio di errore indica che non c'è nulla da ripetere?
È necessario sfuggire alle barre rovesciate: non lo fanno nel motore regex mentre vengono convertiti durante la normale fase di elaborazione delle stringhe Python. A causa di ciò, ha funzionato solo incidentalmente nella versione compressa. Inoltre, cerca "stringhe di stringhe raw" :-) – Cameron
@Cameron, grazie, ho pensato che, poiché stavo usando una citazione tripla, non dovevo sfuggire alle barre. Ho fatto come hai detto e ora ho una fine inaspettata del pattern e ho visto esempi in cui non sono sfuggiti alle backslash o usare una r davanti alla stringa – PyNEwbie