B4J Question Regex Matcher and Patterns

stevel05

Expert
Licensed User
Longtime User
I've wrapped the java.util.regex.Pattern Class as a support for something else I am working on, but I just wanted to make sure that the existing Regex matcher won't provide the same result somehow.


My knowledge of Regex is very limited so I thought I'd ask before releasing a Pandora's box library that I may live to regret.

My final working code looks like this (it is a modified port from a java example of the main project I am working on):

B4X:
'Setup for pattern matching
    Sub InitializePatterns
        KEYWORD_PATTERN = $"\b(${Utils.StringJoin("|", Utils.GetKeywords)})\b"$
        TYPES_PATTERN = $"\b(${Utils.StringJoin("|", Utils.GetTypes)})\b"$
        STRING_PATTERN = "("".*""|\$"".*""\$)"
        COMMENT_PATTERN = $"'.*"$
        Pattern1.Initialize
        Pattern1 = Pattern1.Compile($"(?<KEYWORD>${KEYWORD_PATTERN})|(?<TYPES>${TYPES_PATTERN})|(?<STRING>${STRING_PATTERN})|(?<COMMENT>${COMMENT_PATTERN})"$)
    End Sub

    'Create the style types for matching words
    Sub ComputeHighlighting(Text As String) As JavaObject

        Dim PMatcher As PatternMatcher = Pattern1.Matcher(Text)
    
        Dim SpansBuilder As JavaObject
        SpansBuilder.InitializeNewInstance("org.fxmisc.richtext.StyleSpansBuilder",Null)
    
        Dim Collections As JavaObject
        Collections.InitializeStatic("java.util.Collections")
    
        Dim LastKwEnd As Int = 0
        Dim StyleClass As String

        Do While PMatcher.Find
            StyleClass = ""
            If PMatcher.Group3("COMMENT") <> "null" Then
                StyleClass = "comment"
            Else
                If PMatcher.Group3("STRING") <> "null" Then
                    StyleClass = "string"
                Else
            
                    If PMatcher.Group3("KEYWORD") <> "null" Then
                        StyleClass = "keyword"
                    Else
                        If PMatcher.Group3("TYPES") <> "null" Then
                            StyleClass = "types"
                        End If
                    End If
                End If
            End If
            SpansBuilder.RunMethod("add",Array(Collections.RunMethod("emptyList",Null),PMatcher.Start - LastKwEnd))
            SpansBuilder.RunMethod("add",Array(Collections.RunMethod("singleton",Array(StyleClass)),PMatcher.End_ - PMatcher.Start))
            LastKwEnd = PMatcher.End_
        Loop
        SpansBuilder.RunMethod("add",Array(Collections.RunMethod("emptyList",Null),Text.Length - LastKwEnd))
        Return SpansBuilder.RunMethod("create",Null)    
    End Sub

Can I use the current Matcher to acheive the same result?

SpansBuilder is from another class that this is supporting.
 

stevel05

Expert
Licensed User
Longtime User
Thanks Erel, I persevered and have sorted it now. But I have an almighty headache :confused:
 
Upvote 0
Top