rishav
rishav

Reputation: 481

Validating whether a String is either starting or ending with a specified character using Regular Expression

I need to validate an input String such that it is allowed to have characters 'E', 'W', 'N', 'S' (or their lowercase counterparts) only at either the beginning or at the end of a string(not both). The character will be followed by digits. The character cannot be between digits. Also, if it is present at the beginning then it cannot be at the end(and vice versa).

I was able to come up with this regex: [wWeEnNsS]{0,1}\\d+ that only checks the characters at the beginning. But how do I make sure that if it is present in the beginning then it can not be at the end?

Following are examples of valid inputs:

w234,
W234,
E234,
234w,
234

Invalid inputs:

w234w,
2w34,
ww234,
we234,
w234e,
w

Upvotes: 0

Views: 692

Answers (1)

The fourth bird
The fourth bird

Reputation: 163277

You might use an alternation using the case insensitive mode matching:

^[ewns][0-9]+$|^\d+[ewns]?$

In Java

String regex = "^(?:[ewns]?[0-9]+|\\d+[ewns])$";
  • ^[ewns][0-9]+$ Start of string, match 1 of the listed chars and end of string
  • | Or
  • ^\d+[ewns]?$ Start of string, optionally match 1 of listed chars and end of string

Regex demo | Java demo

Upvotes: 3

Related Questions