newLISP Fan Club

Forum => Anything else we might add? => Topic started by: alex on May 12, 2007, 02:13:15 AM

Title: How I can check regex-string?
Post by: alex on May 12, 2007, 02:13:15 AM
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)
Title:
Post by: newdep on May 12, 2007, 03:16:35 AM
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.
Title:
Post by: cormullion on May 12, 2007, 04:53:35 AM
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...
Title:
Post by: Jeff on May 12, 2007, 06:00:42 AM
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...)).
Title:
Post by: cormullion on May 12, 2007, 06:18:46 AM
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:"
Title:
Post by: Jeff on May 12, 2007, 05:22:29 PM
(catch (regex needle haystack))
Title:
Post by: Lutz on May 12, 2007, 06:49:42 PM
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
Title:
Post by: alex on May 13, 2007, 06:27:00 AM
Very good!

Thanks Your Lutz!  :-)