Forum Discussion

boneyard's avatar
May 06, 2012

checking string on occurrence of characters

im looking for a way to check if a string contains any of these 4 characters: { } [ ] (might add more later). tried this with scan, but somehow it doesn't want to work, i can find the character but im missing a way to differentiate between a hit and not.

 

 

is there another function to try? findstr might be an option but ill end up with doing it 4 times then right?

 

 

the string which has to be checked can be pretty much anything:

 

[

 

]

 

[]

 

hi[bye]test

 

[something]

 

[[[[]]][[[]

 

 

1 Reply

  • I'm not sure how to use a ] in a string match character set. This works for a [:

    % string match {[[]} \[

    1

    But none of these work for a ]:

    % string match {[]]} \]

    0

    % string match {[\]]} \]

    0

    % string match {[\\]]} \]

    0

    % string match {[\\\]]} \]

    0

    % string match {[\\\\]]} \]

    0

    Escaping the right square brace with a backslash works when the brace is not in a string match character set:

    % string match {\]} \]

    1

    For scan, you can put the right square bracket first in the character list and it works:

    % scan \] {%[]]} match; puts $match

    ]

    So if you can assume there is at least one non-matching character first, you could try this:

    scan $string {%*[^][{}]%[][{}]%*s} match

    Or if you can't guarantee at least one non-matching character first, you could try this:

    
    if { [scan $string {%*[^][{}]%[][{}]%*s} match] == 1 || [scan $string {%[][{}]%*s} match]} {
        found $match
    } else {
        no match
    }
    

    Aaron