Regex to match a string starting and ending with a pattern

1127 views java
3

I am trying to write a regex. Condition is that it should not start or end with forward slash (/).

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

answered question

try ^[^\/]+$ this one

2 Answers

10

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

posted this
13

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.

posted this

Have an answer?

JD

Please login first before posting an answer.