Domanda

I'm looking for a regular expression that will match anything that doesn't contain a backslash. I've been trying regexes out on http://regex101.com/#PCRE but neither that not Google is really helping.

I'd like to match any URL string that looks like it has just one slash in the path:

/path/page
/path/anypage

And not match any URL with more slashes:

/path/morepath/page
/path/morepath/andmorepath/page

So far, my regex looks like \/path\/[a-z]+, but that happily matches the URLs with more slashes in too.

How can I exclude these URLs?

È stato utile?

Soluzione

With a negative lookahead, or with a negated class.

Negated class:

^/path/[^/]*$

demo

A negated class will match everything except what's inside, in this case, a forward slash and the anchor $ at the end ensures that the string is tested till the end.

Negative lookahead:

^/path/(?!.*/)

demo

A negative lookahead will make the whole match fail if what's inside matches. So, if .*/ matches at the point of the negative lookahead, the match will fail.

Note: I usually use delimiters that uses characters not appearing in my regex. In this case, I change the delimiters from / to ~.

Altri suggerimenti

this should work :

^(?:\/\w+){2}$

demo here : http://regex101.com/r/gM4nG9

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top