How I can check regex-string?

Started by alex, May 12, 2007, 02:13:15 AM

Previous topic - Next topic

alex

Excuse me for bad English :( ,



I want give to my user possibility enter regular expresson.



How can I check, that the expression is right?



example:

> (set 'test ".?")
".?"
> (regex test "abcde")
("a" 0 1)
> (set 'test "?")
"?"
> (regex test "abcde")

regular expression in function regex : "offset 0 nothing to repeat:"
>


I want know about

  is the "test" right regular expression

before I use (regex)

newdep

#1
I think you might want to turn it around.. every input is allowed unless you

get an unknown return value, like the error you displayed..



You could build a 'catch around it...



Norman.
-- (define? (Cornflakes))

cormullion

#2
This looks ungainly to me:


(set 'user-input "ab")
(set 'test-string "abcde")

(set 'regex-command (string {(} {regex [text]} user-input {[/text] [text]} test-string {[/text])}))
(set 'r (eval-string regex-command 'failed))


If r is 'failed, the regex failed; otherwise it's the result of the regex function.



There's probably a smoother way to do this...

Jeff

#3
You could do something like:


(or (regex 'user-inputed-pattern 'some-string) (some-action 'in 'the 'event 'that 'regex 'evaluates 'to 'nil))

Or use


(if (regex...) (do something...) (do something else...)).
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

cormullion

#4
But isn't Alex's problem that a failed regex stops execution?


(or
  (regex ".+?+" "a string")
  (println "did we get here?"))

regular expression in function regex : "offset 6 nothing to repeat:"

Jeff

#5
(catch (regex needle haystack))
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

Lutz

#6
Jeff is on the right track, but you have to use the second syntax of 'catch' with the extra parameter symbol to check for error exceptions:


(catch (regex ".+?+" "a string") 'result)

If the there was an error the whole expression will return 'nil' and you have the error message in 'result'.



Else if the whole expression returns 'true', there was no error and you can inspect 'result' for the result of the the 'regex' expression, which still may be 'nil' if there was no match. Here is the whole picture:


(catch (regex ".+?+" "a string") 'result) => nil

result => regular expression in function regex : "offset 3 nothing to repeat:"

(catch (regex "r" "a string") 'result) => true

result => ("r" 4 1)

(catch (regex "x" "a string") 'result) => true

result => nil


Lutz

alex

#7
Very good!

Thanks Your Lutz!  :-)