StrCSpn, StrCSpnReverse: Scan strings for characters

From NSIS Wiki
Jump to navigationJump to search
Author: Afrow UK (talk, contrib)


Description

These functions allow you to scan strings for characters.

For both functions, the first invalid character found is returned, else null ("") is returned if no invalid characters are found.

StrCSpn

Description

This function (StrCSpn) checks a string for invalid characters on a list.

Example of Usage

Push "`¬¦!$\"£$$%^&*()_-+={[]}:;@'~#<>,.?/\| $\t"
Push "This string contains at least one of them!"
 Call StrCSpn
Pop $R0 ; $R0 == !
StrCmp $R0 "" +2
 MessageBox MB_OK|MB_ICONEXCLAMATION 'String contains invalid character: $R0'

The Function

Function StrCSpn
 Exch $R0 ; string to check
 Exch
 Exch $R1 ; string of chars
 Push $R2 ; current char
 Push $R3 ; current char
 Push $R4 ; char loop
 Push $R5 ; char loop
 
  StrCpy $R4 -1
 
  NextChar:
  StrCpy $R2 $R1 1 $R4
  IntOp $R4 $R4 - 1
   StrCmp $R2 "" StrOK
 
   StrCpy $R5 -1
 
   NextCharCheck:
   StrCpy $R3 $R0 1 $R5
   IntOp $R5 $R5 - 1
    StrCmp $R3 "" NextChar
    StrCmp $R3 $R2 0 NextCharCheck
     StrCpy $R0 $R2
     Goto Done
 
 StrOK:
 StrCpy $R0 ""
 
 Done:
 
 Pop $R5
 Pop $R4
 Pop $R3
 Pop $R2
 Pop $R1
 Exch $R0
FunctionEnd

StrCSpnReverse

Description

This function (StrCSpnReverse) checks a string for invalid characters not on a list.

Example of Usage

Push "abcdefghijklmnopqrstuvwxyz "
Push "This string contains at least one of them!"
 Call StrCSpnReverse
Pop $R0 ; $R0 == !
StrCmp $R0 "" +2
 MessageBox MB_OK|MB_ICONEXCLAMATION 'String contains invalid character: $R0'

The Function

Function StrCSpnReverse
 Exch $R0 ; string to check
 Exch
 Exch $R1 ; string of chars
 Push $R2 ; current char
 Push $R3 ; current char
 Push $R4 ; char loop
 Push $R5 ; char loop
 
  StrCpy $R4 -1
 
  NextCharCheck:
  StrCpy $R2 $R0 1 $R4
  IntOp $R4 $R4 - 1
   StrCmp $R2 "" StrOK
 
   StrCpy $R5 -1
 
   NextChar:
   StrCpy $R3 $R1 1 $R5
   IntOp $R5 $R5 - 1
    StrCmp $R3 "" +2
    StrCmp $R3 $R2 NextCharCheck NextChar
     StrCpy $R0 $R2
     Goto Done
 
 StrOK:
 StrCpy $R0 ""
 
 Done:
 
 Pop $R5
 Pop $R4
 Pop $R3
 Pop $R2
 Pop $R1
 Exch $R0
FunctionEnd

Credits

Written for Yurik in this forum topic.