Page 1 of 1

How to check if special character is present in the message?

Posted: Wed Aug 23, 2023 5:39 am
by akira463
Please do help , im having a hard time fixing my code, but still it does not work , i only want to check if the certain special character is present in the message
here's my code
:local message "!Your message here"
:local specialChars "!@#$%^&*"
:local found false

:foreach char in=$message do={
    :foreach special in=$specialChars do={
        :if ($char ~ $special) do={
            :set found true
            :log warning "found"
        }
    }
}

Re: How to check if special character is present in the message?

Posted: Wed Aug 23, 2023 6:16 am
by Amm0
Strings are NOT arrays, so you cannot loop char-by-char in RouterOS script. You can however use a regex on the original string to do this check for "bad chars". The only issue is "$" is a special char to RouterOS, so the $ dollar-sign needs to be escaped with backslash like \$

In the most basic form, this works:
:put ("bad string!"~"[!@#\$%^&*]")

As a check, this "throws" an error if "bad string" – again the $ must be escaped since that mean a variable name is next in RouterOS...
:global messageText "bad string!!! & *even bad word d@c% or s#\$%"
:if ($messageText~"[!@#\$%^&*]") do={
    :error "bad char detected"
} 

Re: How to check if special character is present in the message?

Posted: Wed Aug 23, 2023 6:20 am
by Amm0
So your code should be just:
{
  :local message "!Your message here"
  :local specialChars "[!@#\$%^&*]"
  :local found false

  :if ($message ~ $specialChars) do={
      :set found true
      :log warning "found"
  }
}

Re: How to check if special character is present in the message?

Posted: Wed Aug 23, 2023 2:27 pm
by rextended
A little function... just add your unwanted characters after \FF. If is "-" unwanted, must be put at the end.
For default \01-\19\7F-\FF check for any characters that RouterOS do not support.

Simply return true if is present at least one invalid charactes present on passed string, or false if no invalid character is found.
{
:local invalidchr do={:if ($1~"[\01-\19\7F-\FF\24\3F\\\60]") do={:return true} else={:return false}}
# on the example RegEx \24 is the Dollar symbol and \3F is the question mark, \\ is the \, and \60 are the ` (is not the ' )

:put [$invalidchr ("test invalid \$")]
}

Re: How to check if special character is present in the message?

Posted: Wed Aug 23, 2023 4:10 pm
by akira463
Thank you so much masters! now it works!!!