tags:

views:

127

answers:

7

I am trying to use Regex to find out if a string matches *abc - in other words, it starts with anything but finishes with "abc"?

What is the regex expression for this? I tried *abc but "Regex.Matches" returns true for xxabcd, which is not what I want.

+8  A: 

abc$

You need the $ to match the end of the string.

CanSpice
I think I found the answer: ^.*abc\z"
Yep, $ works as well...
The difference between `$` and `\Z` is that `$` will match the end of a line. If you have a carriage return in your string, it'll match right before the carriage return. `\Z` will match the end of the string regardless of if it has carriage returns or not.
CanSpice
+4  A: 
.*abc$

should do.

Tim Pietzcker
you don't really need the `.*`
nico
Correct. It depends on whether he wants to do more than just check the string - perhaps do something with the match afterwards.
Tim Pietzcker
keep the `.*` and it will "consume" all the characters before it (i.e. they'll be part of the "match"); remove it and only `abc` will be "matched"
Brad
@nico: It depends on the mode of search. With regex searching (Python: `re.search("abc$", "bla abc")`), you don't need `.*`, but with "matching" (Python: `re.match("abc$", "bla abc")`) you need it because the regex library tries to match the string from the beginning.
AndiDog
+1  A: 

Try this instead:

.*abc$

The $ matches the end of the line.

Stargazer712
+1  A: 
^.*abc$

Will capture any line ending in abc.

leppie
+4  A: 

So you have a few "fish" here, but here's how to fish.

  • An online expression library and .NET-based tester: RegEx Library
  • An online Rbuy-based tester (faster than the .NET one) Rubular
  • A windows app for testing exressions (most fully-featured, but no zero-width look-aheads or behind) RegEx Coach
Brad
I've been looking for a basic guide to regular expressions and this looks like a handy reference. +1
mlms13
+1 for teaching instead of solving
xPheRe
+1  A: 

It depends on what exactly you're looking for. If you're trying to match whole lines, like:

a line with words and spacesabc

you could do:

^.*abc$

Where ^ matches the beginning of a line and $ the end.

But if you're matching words in a line, e.g.

trying to match thisabc and thisabc but not thisabcd

You will have to do something like:

\w*abc(?!\w)

This means, match any number of continuous characters, followed by abc and then anything but a character (e.g. whitespace or the end of the line).

steinar
I think your answer represent what the user wants... using the \w parameter, you will catch any words that ends with abc.
dutertimes
A: 

If you want a string of 4 characters ending in abc use, /^.abc$/

David Harris