Page 1 of 1

How I can check regex-string?

Posted: Sat May 12, 2007 9:13 am
by 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:

Code: Select all

> (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)

Posted: Sat May 12, 2007 10:16 am
by newdep
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.

Posted: Sat May 12, 2007 11:53 am
by cormullion
This looks ungainly to me:

Code: Select all

(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...

Posted: Sat May 12, 2007 1:00 pm
by Jeff
You could do something like:

Code: Select all

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

Code: Select all

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

Posted: Sat May 12, 2007 1:18 pm
by cormullion
But isn't Alex's problem that a failed regex stops execution?

Code: Select all

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

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

Posted: Sun May 13, 2007 12:22 am
by Jeff

Code: Select all

(catch (regex needle haystack))

Posted: Sun May 13, 2007 1:49 am
by Lutz
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:

Code: Select all

 (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:

Code: Select all

(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

Posted: Sun May 13, 2007 1:27 pm
by alex
Very good!
Thanks Your Lutz! :-)