Asterisks: Convert To Regexp

Posted by Xvordan on Mon 11 Apr 2016 11:08 PM — 2 posts, 13,149 views.

#0
Whenever I have a trigger/etc pattern which contains actual asterisks, the convert to regular expression function wants to represent them as (.*)? rather than as \*. Is there any reason that I'm missing for this behavior? (.*)? looks weird and inaccurate (at best) to me. I always have to go through the converted string and change the results to \*.
Australia Forum Administrator #1
The behaviour is correct. First, you need to make a "capture" which is why the brackets are there. If you don't happen to want a capture then you can omit the brackets.

For example:


Match: punch *     (non-regexp)
Match: punch (.*?) (regexp)
Send:  punch %1


The asterisk represents the capture into wildcard %1.

However if you just happen to have variable stuff that doesn't need capturing then .* is OK.




The "?" makes the wildcard non-greedy.

See my page about regular expressions: http://www.gammon.com.au/regexp


Groups and tagged expressions

The default behaviour is for each group to be returned as a "wildcard" for the trigger or alias...


Regexp: tell (.+) (.+)
Match : tell Nick hi there
Wildcard '1' = 'Nick hi'
Wildcard '2' = 'there'


However you can see a problem here, the first wildcard is "Nick hi" where we really want it to be the name. So we need to make it less greedy:


Regexp: tell (.+?) (.+)
Match : tell Nick hi there
Wildcard '1' = 'Nick'
Wildcard '2' = 'hi there'


The default for the non regexp wildcards is non-greedy matches, which is why the convert to regexp does that.

In fact, internally, all non-wildcard matches are converted using the same algorithm, so they are regexps by the time they are used.