[Zope] How to check if a string contains some characters??

Casey Duncan cduncan@kaivo.com
Mon, 12 Mar 2001 09:03:38 -0700


Tino Wildenhain wrote:
> 
> Hi,
> 
> in pure python you can also write:
> # -------------------------------------------------
> import re
> 
> if re.search(r"[^A-Za-z0-9\.\-_]",string_name):
>         raise Exception("illegal character here.")
> 
> # -------------------------------------------------
> 
> However this is untested. But you get the idea ;)
> re is certainly faster then in-loops.
> 
> Regards
> Tino
> 
> "Spicklemire, Jerry" wrote:
> >
> > Marcello asked:
> >
> > > Is there a simple way to check if a string contain only this values:
> > > "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_"
> > > and otherwise raise an error?
> >
> > If you have a string you want to check, with the name "string_name":
> >
> > <dtml-call "REQUEST.set('char_invalid', 'no')">
> > <dtml-let
> > chars_valid="'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
> > .-_'">
> >  <dtml-while "char_valid == 'no'">
> >   <dtml-in string_name>
> >    <dtml-if "sequence-item !in chars_valid">
> >     <dtml-call "REQUEST.set('char_invalid', 'yes')">
> >    </dtml-if>
> >   </dtml-in>
> >  </dtml-while>
> > </dtml-let>
> > <dtml-if "char_invalid == 'no'">
> >  <dtml-call "your raise_error_code">
> > </dtml-if>
> >
> > This may not look as simple as you want, but in pure Python,
> > (without alls the <dtml-stuff > this would be:
> >
> > string_valid = 'yes'
> > for char in string_name :
> >         if char !in
> > 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_' :
> >                 string_valid = 'no'
> >                 break
> >
> > if string_valid == 'no' :
> >         (run your "raise error" code here)
> >
> > Later,
> > Jerry S.
> >

FYI:

There is no dtml-while tag.
You cannot iterate a string with dtml-in 8^(
To do this in dtml, the best thing is probably something like:

set a tokens property called allowed_chars on the folder executing the
method (or the root). This property should have all the allowed
characters in it separated by spaces. Then use this DTML (untested):

<dtml-in expr="_.range(_.len(string))">
	<dtml-unless expr="string[_['sequence-item']] in allowed_chars">
		<dtml-raise InvalidString>Invalid String</dtml-raise>
	</dtml-unless>
</dtml-in>

The performance of this would be much less than using an external python
method and regular expressions however.
	
-- 
| Casey Duncan
| Kaivo, Inc.
| cduncan@kaivo.com
`------------------>