RegEx Exception - Why?

Hi everyone and merry christmas.

I’ve this RegEx-Pattern, which works fine with Kems RegExRX:
^(<|>)?\s*(?:(?:(\d{1,3})\s*(?:y)\s*)?(?:(\d{1,2})\s*(?:m)\s*)?(?:(\d{1,2})\s*(?:d))?)$

But in Xojo this code crashs. Why?

[code]dim rx as new RegEx
rx.SearchPatterm = “^(<|>)?\s*(?:(?:(\d{1,3})\s*(?:y)\s*)?(?:(\d{1,2})\s*(?:m)\s*)?(?:(\d{1,2})\s*(?:d))?)$”

dim match as RegExMatch = rx.Search(“10y 24m”)

if match <> nil then
dim oPrefix as Text = match.SubExpressionString(1).ToText
dim oYears as Text = match.SubExpressionString(2).ToText
dim oMonths as Text = match.SubExpressionString(3).ToText
dim oDays as Text = match.SubExpressionString(4).ToText // Debugger crashs. Why?
end if[/code]

Thanks to everyone!

How many matches do you get in RegExRx?

I’ll get 3 matches. The thing is i need also the Nil matches, because every part of the SearchString is optional:

  • Prefix (<, >)
  • Years
  • Months
  • Days

It’s important to match all parts, because i’ve to create an object with the values returned.

Use Try…Catch around the statement for each sub expression string. If the exception is caught then you know the field is nil to use later in your code.

There is no crash. You are simply missing a check for SubExpressionCount.

I think Beatrix is right. If the match text looks like “< 23y 13m”, you will only get three, not four, subgroups. Try something like this:

  dim oPrefix as Text = if( match.SubExpressionCount > 1, match.SubExpressionString(1).ToText, "" )
  dim oYears as Text = if( match.SubExpressionCount > 2, match.SubExpressionString(2).ToText, "" )
  dim oMonths as Text = if( match.SubExpressionCount > 3, match.SubExpressionString(3).ToText, "" )
  dim oDays as Text = if( match.SibExpressionCount > 4, match.SubExpressionString(4).ToText, "" )

Or use the code you have and put parens around the last “$” to force five subgroups in every match.

Thanks Beatrix and Kem for the input :slight_smile: