2017-11-25 3 views
1

Ich Parsing Java-Quellcode mit Python. Ich muss den Kommentartext aus der Quelle extrahieren. Ich habe Folgendes versucht.Python Regex zum Extrahieren von Java-Kommentar

Take 1:

cmts = re.findall(r'/\*\*(.|[\r\n])*?\*/', lines)

Returns: Rohlinge [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

2 Nehmen: (hinzugefügt, um eine Gruppierung Klammer um die regex)

cmts = re.findall(r'(/\*\*(.|[\r\n])*?\*/)', lines)

Returns

Einzeiliger Kommentar (nur als Beispiel):

('/**\n\n * initialise the tag with the colors and the tag name\n\n */', ' ')

mehrzeiliger Kommentar (nur als Beispiel):

('/**\n\n * Get the color related to a specified tag\n\n * @param tag the tag that we want to get the colour for\n\n * @return color of the tag in String\n\n */', ' ')

Ich interessiere mich nur in initialise the tag with the colors and the tag name oder Get the color related to a specified tag, @param tag the tag that we want to get the colour for, @return color of the tag in String und bin nicht in der Lage Mach meinen Kopf drum herum. Bitte gib mir ein paar Hinweise!

Antwort

1

extrahieren Kommentare (alles zwischen /** und */) können Sie verwenden:

re.findall(r'\*\*(.*?)\*\/', text, re.S) 

(beachten Sie, wie Capture-Gruppe vereinfacht werden kann, wenn re.S/re.DOTALL verwendet wird, wenn Punkt auch Zeilenumbrüche Spiele).

Dann wird für jedes Spiel können Sie mehrere Leerzeichen/* und ersetzen \n mit , Streifen:

def comments(text): 
    for comment in re.findall(r'\*\*(.*?)\*\/', text, re.S): 
     yield re.sub('\n+', ',', re.sub(r'[ *]+', ' ', comment).strip()) 

Zum Beispiel:

>>> list(comments('/**\n\n  * Get the color related to a specified tag\n\n  * @param tag the tag that we want to get the colour for\n\n  * @return color of the tag in String\n\n  */')) 
['Get the color related to a specified tag, @param tag the tag that we want to get the colour for, @return color of the tag in String'] 
Verwandte Themen