Forum Discussion

YoJae's avatar
YoJae
Visitor
10 years ago

roRegex count characters in given string

Hi guys,

I am struggling with regular expression to count how many characters does a string contains.

I am using Match command which should output an array of characters.
These are my commands in the debugger:

BrightScript Debugger> ra = createObject("roRegex", "(a)", "")
BrightScript Debugger> ? ra.Match("ha |fg d a a aa a a |")
a
a


As you can see it only outputs 2 "a" characters and an empty character.
My idea was to get count() of the array.

How can I match characters or is there any better way for this?
Many thanks

4 Replies

  • Unfortunately, the regex implementation on the Roku only supports finding the first match in a string. There's no way that I'm aware of to find all matches. You could potentially use roRegex.Split to split the string into an array and count the entries, but that may drop empty strings.
  • It's probably simpler to just iterate through the characters rather than using roRegex for this.

    --Mark
  • Thanks for your suggestion, this may do the trick 😉
  • "TheEndless" wrote:
    You could potentially use roRegex.Split to split the string into an array and count the entries, but that may drop empty strings.

    roRegEx.split() does not drop empty strings. So it will work but is brutal. Here is a slightly better way:
    BrightScript Debugger> s = "ha |fg d a a aa a a |"
    BrightScript Debugger> ? len(s) - len(s.replace("a", ""))
    7
    roRegEx.replaceAll() can do the same for a pattern - or if multiple stats are to be accounted, just roll over the string and collect in a dictionary.