4/28/2010

LS2J: Replace string by using regular expression

I introduced the sample code to use regular expression but some of guys still believe that this kind of code can be performed by using @contains or other LotusScript code.. I should have used more complicated matching to show the power of regular expressions.

As more practical sample, today I'd like to introduce another sample code to use regular expressions. (still not complicated)

Regular expression is very powerful when you want to replace the chunk of strings.
Please note that LS2J needs to load jvm when running the agent. so intensive use of this function might be slower than normal LotusScript application.




Uselsx "*javacon"
Sub Click(Source As Button) Dim b As Boolean teststr$ = "[09D4:000D-0D50] 2008/09/18 15:45:26 HTTP Server: Error - Memory allocation error" ' Regular expression to match Thread ID part ([09D4:000D-0D50]) regex$ = "\[[\p{Alnum}:-]*\]" ' regex$ = "\[[a-zA-Z0-9:-]*\]" replacedstr$ = "" result$ = ReplaceString(testStr$,regex$, replacedstr$) Msgbox "Input: " & teststr$ & Chr(13) & "Pattern: " & regex$ &; " -> " &; replacedstr$ &a; Chr(13) & result$ End Sub Function ReplaceString(InputStr As String , RegEx As String, ReplacedStr As String) As String ' RepleaceString: This function is to replace the string by using regular expression. ' See following reference site for Java regular expressions
' URL: http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/util/regex/Pattern.html ' InputStr: Strings to be replaced
' RegEx: Regular expression to replace target string ' ReplacedStr: Strings To Replace ' Return Value: Replaced String ' Note: Do not forget declaring Uselsx "*javacon" Dim j As JavaSession Dim c As JavaClass Dim pattern As JavaObject Dim matcher As JavaObject Dim e As JavaError Set j = New JavaSession Set c = j.GetClass("java.util.regex.Pattern") Set pattern = c.compile(RegEx) Set matcher = pattern.matcher(InputStr) ReplaceString = matcher.replaceAll(ReplacedStr) End Function
Hope it helps!

No comments:

Post a Comment