Regular Expression, Match previous word

Posted by Joseisme on Wed 07 Nov 2012 04:42 AM — 5 posts, 21,194 views.

#0
I am trying to figure out a way to match any one word before a known word.

In these examples I am trying to match the word before 'has' so I can pass it on to other triggers so my client knows what has just died.

I am matching these.
Quote:

A dirty rat has been defeated.

or

An ancient red spirit has been defeated.


For these examples I only want the words 'rat' or 'spirit'. Not 'dirty rat' or 'ancient red spirit'. The exact number of adjectives before the main word is unknown but the following word 'has' is constant.

I have tried this but I only get 'rat has' at %3.
Quote:

^(A|a|an|An|the|The) (.*?) (.*? has) been defeated\.$


How can I get this to work so it matches the word just before 'has'?

(Using Mushclient version 4.73)
Australia Forum Administrator #1
This, maybe?


<triggers>
  <trigger
   custom_colour="2"
   enabled="y"
   match="^(A|a|an|An|the|The) (.*) ((\w+) has) been defeated\.$"
   regexp="y"
   send_to="2"
   sequence="100"
  >
  <send>
%%1 = %1
%%2 = %2
%%3 = %3
%%4 = %4
</send>
  </trigger>
</triggers>


Template:pasting
For advice on how to copy the above, and paste it into MUSHclient, please see Pasting XML.


Output from your test data:


A dirty rat has been defeated.
%1 = A
%2 = dirty
%3 = rat has
%4 = rat

An ancient red spirit has been defeated.
%1 = An
%2 = ancient red
%3 = spirit has
%4 = spirit


Nested wildcards saved the day. :)
Amended on Wed 07 Nov 2012 05:55 AM by Nick Gammon
Australia Forum Administrator #2
Or reduce the number of wildcards:


<triggers>
  <trigger
   custom_colour="2"
   enabled="y"
   match="^(?:A|a|an|An|the|The) .* (\w+) has been defeated\.$"
   regexp="y"
   send_to="2"
   sequence="100"
  >
  <send>
%%1 = %1
</send>
  </trigger>
</triggers>


Output:


A dirty rat has been defeated.
%1 = rat

An ancient red spirit has been defeated.
%1 = spirit
Australia Forum Administrator #3
Template:regexp
Regular expressions
  • Regular expressions (as used in triggers and aliases) are documented on the Regular expression tips forum page.
  • Also see how Lua string matching patterns work, as documented on the Lua string.find page.
#4
As always thanks for the reply, that worked like a charm. You also taught me some very useful tricks which I plan to apply to a few other triggers.