-4

I need to check if a string last word is either "...abc" or "...xyz" or "...fgh".

How i can achieve the same thing using regex as i am trying to learn it?

e.g Sentence 1: Hi My Name is abc. Sentence 2: I live in xyz.

The above sentence is a sample one to demonstrate.

Nishant Kumar
  • 463
  • 2
  • 9
  • 18
  • 4
    Do you know how to check if a string is *exactly* either “abc”, “xyz”, or “fgh” with regex? – Ry- Jul 17 '17 at 07:05

2 Answers2

5

You don't need any Regex. Just use String.EndsWith :

string a = "asdasd abc";

Console.WriteLine(a.EndsWith("abc.") || a.EndsWith("xyz.") || a.EndsWith("fgh."));
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
  • How are you going to check for 3 possibilities using `EndWith()`? You'll need to run it 3 times which is wasteful. What if you need to check for 10 possibilities? – Racil Hilan Jul 17 '17 at 07:18
  • @RacilHilan no, I don't need to run 3 times. `||` will work until first `true`. – Samvel Petrosov Jul 17 '17 at 07:19
  • @RacilHilan in addition, How do you think your regex will work? It will check for 3 cases as well. – Samvel Petrosov Jul 17 '17 at 07:20
  • Yes, it will return the first `true`, but what if it is the last? Then it runs 3 times. And if you need 10 options, then it runs 10 times. And no, regex does not run 3 (or 10 times). Read how regex works. If you benchmark the two solutions, you'll see a big difference. Also repeating the code 3 times (or 10) is really tiring for the eyes :-) – Racil Hilan Jul 17 '17 at 07:23
  • @RacilHilan as you can see at screenshot it is not exactly that Regex will work better or faster. http://take.ms/Bc58f – Samvel Petrosov Jul 17 '17 at 07:32
  • 1
    Quick benchmarking :-). But it's not that simple, you need a much bigger loop and you need to compile the regex. There are people who already benchmarked it on SO, but have a quick look at [this explanation of how regex works](https://stackoverflow.com/a/37584635). I hope you'll find it useful. Basically, regex is kind of scripted language. For simple cases (e.g. compare only one value) `EndWith` is definitely faster, but for more complex cases (like we're doing here) regex uses smarter methods. – Racil Hilan Jul 17 '17 at 07:44
2

You can use this simple regex pattern:

(abc|xyz|fgh)$

Put your possible options between parenthesis separated by pipes. The $ means the end of the string.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55