VB(Excel)中的RegEx-如何对此进行解码

时间:2019-02-04 07:12:22

标签: regex excel vba

在阅读了有关如何在MS Excel中使用RegEx的非常有用的post信息之后,我现在停留在生成所需的表达式以涵盖以下场景的过程中-感谢您的帮助。

目标:我希望能够分割如下字符串:

示例1:

  

AB12345|AB56789x89402 ---> AB12345 AB56789 89402(要存储在不同单元格中的三个中的每一个和子字符串的总数在提前,可能是0到10)

示例2:

  

#AB03925#要存储为AB03925

示例3:

  

(ABC-SR-XYZ)|(ABC-XYZ)要存储为ABCXYZ

是否可以通过单个RegEx处理以上所有示例?

到目前为止,我已经创建了以下示例,可以部分处理示例1:

    strPattern = "(^[A-Z][A-Z][0-9]{5})([|]*[A-Z][A-Z][0-9]{5})"

    If strPattern <> "" Then
        strInput = C.Value

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            C.Offset(0, 1) = regEx.Replace(strInput, "$1")
            C.Offset(0, 2) = regEx.Replace(strInput, "$2")
        End If
    End If

但是,当我分别打印这两个字符串时,我仍然不知道如何摆脱管道(|)。

2 个答案:

答案 0 :(得分:1)

如果您有兴趣,这里是一个非正则表达式的解决方案。

import UIKit

class LoginScreenVC: UIViewController {
    let myTokenHandler = TokenHandler()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func loginButton(_ sender: Any) {
        print("Login button pressed")

        let usernameInputField = self.view.viewWithTag(6548) as! UITextField
        let passwordInputField = self.view.viewWithTag(6549) as! UITextField

        userInput = usernameInputField.text!
        passInput = passwordInputField.text!

        // call completion handler
        requestToken(success: handlerBlock)

    }
    // completion handler step 1: request token and get redirect string to switch screen
    func requestToken(success: (String) -> Void) {
        let requestResult = myTokenHandler.requestToken(password: passInput, username: userInput)
        success(requestResult)
    }

    // completion handler step 2: use redirect string to switch screen
    let handlerBlock: (String) -> Void = { redirect in
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let loginScreen = storyboard.instantiateViewController(withIdentifier: redirect)
            self.present(loginScreen, animated: true, completion: nil) //Value of type '(LoginScreenVC) -> () -> (LoginScreenVC)' has no member 'view'
    }
}

它返回:

Option Explicit

Private Function ConvertCustomText(InputString As String) As Variant
    Dim CharactersToReplace As Object: Set CharactersToReplace = CreateObject("Scripting.Dictionary")
    Dim Character           As Variant
    Dim HasDash             As Boolean

    With CharactersToReplace
        .Add "#", vbNullString
        .Add "(", vbNullString
        .Add ")", vbNullString
        .Add "-", vbNullString
        .Add "x", "|"
    End With

    HasDash = IIf(InStr(1, InputString, "-", vbBinaryCompare) > 0, True, False)

    For Each Character In CharactersToReplace
        InputString = Replace(InputString, Character, CharactersToReplace(Character))
    Next

    ConvertCustomText = IIf(HasDash, _
                            Split(InputString, "|")(UBound(Split(InputString, "|"))), _
                            Split(InputString, "|"))
End Function

Public Sub Example()
    PrintArrayOrText (ConvertCustomText("AB12345|AB56789x89402"))
    PrintArrayOrText (ConvertCustomText("#AB03925#"))
    PrintArrayOrText (ConvertCustomText("(ABC-SR-XYZ)|(ABC-XYZ)"))
End Sub

Private Sub PrintArrayOrText(VariantInput As Variant)
    Dim i As Long

    If TypeName(VariantInput) = "String" Then
        Debug.Print "Output is " & VariantInput
    Else
        For i = LBound(VariantInput) To UBound(VariantInput)
            Debug.Print "Output is " & VariantInput(i)
        Next
    End If

End Sub

答案 1 :(得分:0)

对于示例1 2 ,此正则表达式有效
[A-Z]{2}\d{5}|\d{5} regexstorm中的证明。
enter image description here

要获得不同的结果,可以跨列使用,使用该列设置结果索引。

If regEx.Test(strInput) Then
    Set matches = regEx.Execute(strInput)
    Dim resultSetIndex
    resultSetIndex = Application.Caller.Column - x ' x is your first column

    If resultSetIndex < matches.Count Then
        RegxFunc = matches(resultSetIndex).Value
    Else
        RegxFunc = ""
    End If
    Else
        RegxFunc = "not matched"
End If

Application.Caller.Column用于确定结果索引。
您需要设置x放置列的位置。在下面的示例中,x 7
column to result set
对于示例3 ,您需要详细说明提取规则。
目前尚不完全清楚。