Shravya
Shravya

Reputation: 218

Regular expression starts with a string but not contain a special character after that

I am trying to find a regular expression which basically matches start of a string but not having a specific character after that. By this I should be achieving same level routes.

Example : Lets say I have the following strings and I need to get routes starting from LAX with no stops.

  1. LAX-LAS-JFK
  2. LAX-PHX-JFK
  3. LAX-JFK
  4. LAX-PHX

The regex should match only route 3 and 4.

I have tried this ^LAX-([^-])* and it didn't work for me when I cross checked on https://www.regextester.com/15.

Upvotes: 1

Views: 42

Answers (2)

Salamosaurus
Salamosaurus

Reputation: 124

So it sounds like you want to match with strings that only have 1 dash. Perhaps something like this ^(LAX)(-{1})[a-zA-Z]+$ would work? It will check to make sure the string LAX is in the beginning, followed by one dash and ending with alphabetical characters.

Upvotes: 1

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

You can try this:

^LAX(-[A-Z]+){1}$

This matches

LAX-JFK
LAX-PHX

but not

LAX-LAS-JFK
LAX-PHX-JFK

Demo: regex101


Explanation:

  • ^ start
  • $ end
  • {1} exact number of repetitions of a pattern, in this case 1

Fun fact: you can replace the 1 by (number of stops + 1), and it will select only the routes with the defined number of stops (another example).

Upvotes: 2

Related Questions