Jeff
Jeff

Reputation: 1800

regex check second letter of string

I have a fun little task. I need to set a variable to true if:

string ends in a letter or the second digit in the string is either a "p" or "r".

So far, I have

var endingIsLetter = Regex.(myString.length - 1) ??? magic here.

Any help? My regex buddy is on a dead laptop.

EDIT -- REGEX is not required. I just thought it would be the easiest way to get this done. Any examples are welcome.

Upvotes: 2

Views: 16969

Answers (4)

Frankie Law
Frankie Law

Reputation: 11

var match = Regex.Matches( @"\w(p|r)+*\w", "Eppressio9n" )

Argh, I just kinda did this out of the blue because I have to leave for work at the moment.

I forget what Regex.Matches returns, all you got to do is check if there is anything that returned from Regex.Matches.

Hope this helps

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Recall that . represents a single character, ^ is an anchor for the beginning of string, $ is an anchor for the end of string, and [pr] is any single character from the list between the square brackets.

^.[pr]

means "second letter is p or r.

[A-Za-z]$

means "the last character is a letter".

Console.WriteLine(Regex.IsMatch("abc123", "^.[pr]|[A-Za-z]$")); // False
Console.WriteLine(Regex.IsMatch("abc12x", "^.[pr]|[A-Za-z]$")); // True
Console.WriteLine(Regex.IsMatch("apc123", "^.[pr]|[A-Za-z]$")); // True
Console.WriteLine(Regex.IsMatch("arc123", "^.[pr]|[A-Za-z]$")); // True
Console.WriteLine(Regex.IsMatch("", "^.[pr]|[A-Za-z]$"));       // False

Demo on ideone.

Upvotes: 3

Mario
Mario

Reputation: 36517

You have to use regular expressions? or is this optional? Because code without regular expressions might actually be faster. :)

To match the second character in a string: ^.[pr] To match the last character in a string: [a-z]$

Combined: ^.[pr]|[a-z]$

  • ^ matches the beginning of the string
  • $ matches the end of the string
  • . matches any character (except line breaks depending on your settings)
  • [...] provides a selection "any of these", where you can define ranges as well
  • [a-z] represents any character from the range a through z. Note that this does not include things like umlauts.

Note that the regular expression above expects case-insensitive matching to work properly (otherwise you'd have to add the uppercase characters as well): ^.[PRpr]|[A-Za-z]$

To get a quick preview of regular expressions (in case I'm unsure) I prefer the Regex Hero Tester.

Upvotes: 3

horgh
horgh

Reputation: 18553

Why use Regex for that?

var flag = char.IsLetter(s[s.Length - 1]) || 
           s[1] == 'p' || 
           s[1] == 'r';

Upvotes: 5

Related Questions