regular exp help

L

Luna

I need to write a regular expression that would match the last occurrence of
one of the following words

ABC
123
XYZ
Apple

Apple sdhfjh ABC dsfd df XYZ dfd dfdf dakj
this input would match: XYZ

123 XYZ sdfjksd ABC
this input would match: ABC

TY
Luna
 
J

Jeff Johnson

I need to write a regular expression that would match the last occurrence
of one of the following words

ABC
123
XYZ
Apple

Apple sdhfjh ABC dsfd df XYZ dfd dfdf dakj
this input would match: XYZ

123 XYZ sdfjksd ABC
this input would match: ABC

A regex probably can't do this on its own. While I'm sure you'd like to do
things in one step, I don't believe you can in this case. However, it's not
that hard to write a little code to get your desired result. Simply execute
the regex and get a MatchCollection. Then find out how many entries it
contains and return the value of the last one. Wrap this in a function which
takes the regex pattern and string to test and returns a string and you're
good to go.
 
P

Pavel Minaev

I need to write a regular expression that would match the last occurrenceof
one of the following words

ABC
123
XYZ
Apple

Apple sdhfjh ABC dsfd df XYZ dfd dfdf dakj
this input would match: XYZ

123 XYZ sdfjksd ABC
this input would match: ABC

Try this:

\b(ABC|123|XYZ|Apple)\b(?!.*\b(ABC|123|XYZ|Apple)\b)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top