Seema Kadavan
Seema Kadavan

Reputation: 2648

Regex to match a string not starting or ending with a pattern

I am trying to write a regex. The condition is that it shouldn't start nor end with a forward slash (/).

^[^/].*[^/]$ is the one I have been trying with. This fails if the string has only one character. How should I get this corrected?

Upvotes: 3

Views: 1924

Answers (3)

chandra
chandra

Reputation: 500

Split the pattern into 2 parts:

  1. First Part - not starting with '/'
  2. Optional second part - not ending with '/'.

You can get something like following:

^[^/](.*[^/])?$

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59252

There's a far easier and simpler way to solve this than going with RegEx. So if you are willing, you could simply do:

char first = str.charAt(0); 
char last = str.charAt(str.length() - 1);
if(first != '/' && last != '/') {
  // str is valid.
}

Where str is the string to be checked.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370809

Match the first character, then have an optional group that matches 0+ characters, followed by a non-slash character, followed by the end of the string:

^[^/](?:.*[^/])?$

https://regex101.com/r/Mp674r/2

Upvotes: 2

Related Questions