BattlFrog
BattlFrog

Reputation: 3397

RegEx conditional based on which letter

I have an if statement that I am trying to condense down into a regex statement. The if statement is the following:

 string degree = "21S"
 if (degree != "" && 
     Convert.ToInt32(degree) > 9 && 
     TChr == "N" || 
    degree != "" && 
    Convert.ToInt32(degree) > 41 && TChr == "S")

The string will always be a number and either an S or N (north/south). If it is a N, the number must be between 1-9, if it is an S, the range is 1-41.

I have been trying a range with a conditional:

^(?(/dN)[1-9]N|[1-51]S)$

However, it is not catching anything, so I assume I am going about it the wrong way.

Upvotes: 0

Views: 51

Answers (3)

Alan Moore
Alan Moore

Reputation: 75242

I think you were trying for this:

^(?(?=\dN)[1-9]N|(?:4[01]|[1-3][0-9]|[1-9])S)$

...but you don't really need a conditional for this task. This works just fine:

^(?:[1-9]N|(?:4[01]|[1-3][0-9]|[1-9])S)$

Also, you can't match numbers with regexes (i.e., by their numerical values). Letters, digits, punctuation or whatever, they're all just characters.

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103525

Regex isn't the best tool for this job, because it's difficult to check integer ranges with a regex.

Unless you really have to use regular expressions, I'd just clean up what you have a little. It's much more readable code than a regex that does the same thing.

string input = "21S";
char direction = input.Last();
int degree = int.Parse(input.Trim('N', 'S'));
bool valid = ((direction == 'N' && degree >= 1 && degree <= 9) ||
              (direction == 'S' && degree >= 1 && degree <= 41);

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

You can use the following regex:

\b(?:[1-9]N|(?:[1-9]|[1-3][0-9]|4[01])S)\b

var pattern = @"\b(?:[1-9]N|(?:[1-9]|[1-3][0-9]|4[01])S)\b";

Here is the demo.

enter image description here

Upvotes: 2

Related Questions