Dave
Dave

Reputation: 83

Match specific string, except when it contains certain text

I'm working with urls and have a simple working regex

^go\/([_0-9a-z-])+

which matches anything that starts with "go/"

I now need to extend this so it still matches that, but now only if it doesn't contain another string - in this case ".aspx" (ie I'm trying to match folders, but not filenames)

So successful matches would include

go/test1
go/test2

and unsuccessful ones would include

go/test3.aspx
go/test4.aspx?param
stop/test5

Upvotes: 1

Views: 75

Answers (2)

Code Different
Code Different

Reputation: 93161

  1. Put the + inside the capturing group if you want to match everything after go/
  2. Define a second, optional capturing group for .aspx. Filtering out matches where this second group is not null. Regex isn't the only programming language in town.

Pattern and stub:

^go\/([_0-9a-z-]+)(\.aspx)?

Upvotes: 0

Maroun
Maroun

Reputation: 95958

Change your regex to:

^go\/([_0-9a-z-])+$

The $ matches the end of the string, so no more characters allowed. If you only want to match strings that don't have ".something" after, then you can use look-arounds.

Upvotes: 3

Related Questions