RegEx в VBA: разбить сложную строку на несколько токенов? - PullRequest
2 голосов
/ 10 сентября 2010

Я пытаюсь разобрать строку в файле белка mmCIF в отдельные токены с помощью Excel 2000/2003. В худшем случае это могло бы выглядеть примерно так:

token1 token2 "token's 1a',1b'" 'token4"5"' 12 23.2 ? . 'token' tok'en to"ken

Которые должны стать следующими токенами:

token1  
token2  
token's 1a',1b' (note: the double quotes have disappeared)  
token4"5" (note: the single quotes have disappeared)  
12  
23.2  
?  
.  
token (note: the single quotes have disappeared)  
to'ken  
to"ken  

Я смотрю, возможно ли даже в RegEx разделить линии такого типа на токены?

Ответы [ 2 ]

1 голос
/ 13 сентября 2010

Хорошая головоломка. Спасибо.

Этот шаблон (aPatt ниже) разделяет токены, но я не могу понять, как удалить внешние кавычки.

Tallpaul () производит:

 token1
 token2
 "token's 1a',1b'"
 'token4"5"'
 12
 23.2
 ?
 .
 'token'
 tok'en
 to"ken

Если вы можете выяснить, как потерять внешние кавычки, пожалуйста, сообщите нам об этом. Для работы требуется ссылка на «Регулярные выражения Microsoft VBScript».

Option Explicit
''returns a list of matches
Function RegExpTest(patrn, strng)
   Dim regEx   ' Create variable.
   Set regEx = New RegExp   ' Create a regular expression.
   regEx.Pattern = patrn   ' Set pattern.
   regEx.IgnoreCase = True   ' Set case insensitivity.
   regEx.Global = True   ' Set global applicability.
   Set RegExpTest = regEx.Execute(strng)   ' Execute search.
End Function

Function tallpaul() As Boolean
    Dim aString As String
    Dim aPatt As String
    Dim aMatch, aMatches

    '' need to pad the string with leading and trailing spaces.
    aString = " token1 token2 ""token's 1a',1b'"" 'token4""5""' 12 23.2 ? . 'token' tok'en to""ken "
    aPatt = "(\s'[^']+'(?=\s))|(\s""[^""]+""(?=\s))|(\s[\w\?\.]+(?=\s))|(\s\S+(?=\s))"
    Set aMatches = RegExpTest(aPatt, aString)

    For Each aMatch In aMatches
          Debug.Print aMatch.Value
    Next
    tallpaul = True
End Function
1 голос
/ 10 сентября 2010

Можно сделать:

В вашем проекте VBA вам нужно будет сослаться на «Регулярные выражения Microsoft VBScript 5.5», а затем ...

Private Sub REFinder(PatternString As String, StringToTest As String)
    Set RE = New RegExp

    With RE
        .Global = True
        .MultiLine = False
        .IgnoreCase = False
        .Pattern = PatternString
    End With

    Set Matches = RE.Execute(StringToTest)

    For Each Match In Matches
        Debug.Print Match.Value & " ~~~ " & Match.FirstIndex & " - " & Match.Length & " = " & Mid(StringToTest, Match.FirstIndex + 1, Match.Length)

        ''#You get a submatch for each of the other possible conditions (if using ORs)
        For Each Item In Match.SubMatches
            Debug.Print "Submatch:" & Item
        Next Item
        Debug.Print
    Next Match

    Set RE = Nothing
    Set Matches = Nothing
    Set Match = Nothing
    Set SubMatch = Nothing
End Sub

Sub DoIt()
    ''#This simply splits by space...
    REFinder "([.^\w]+\s)|(.+$)", "Token1 Token2 65.56"
End Sub

Это, очевидно, просто очень простой пример, так как я не очень хорошо осведомлен о RegExp, я просто покажу вам, КАК это можно сделать в VBA (возможно, вы захотите сделать что-то более полезное, чем Debug.Print с полученными токенами!). Я должен оставить запись выражения RegExp кому-то еще, я боюсь!

Simon

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...