[英]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?
我应该如何纠正这个问题?
Split the pattern into 2 parts: 将模式分为两部分:
You can get something like following: 您可以得到如下内容:
^[^/](.*[^/])?$
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: 匹配第一个字符,然后有一个与0+个字符匹配的可选组,然后是一个非斜杠字符,然后是字符串的末尾:
^[^/](?:.*[^/])?$
https://regex101.com/r/Mp674r/2 https://regex101.com/r/Mp674r/2
There's a far easier and simpler way to solve this than going with RegEx. 解决此问题的方法比使用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. 其中
str
是要检查的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.