简体   繁体   English

正则表达式匹配不以模式开头或结尾的字符串

[英]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: 将模式分为两部分:

  1. First Part - not starting with '/' 第一部分-不是以'/'开头
  2. Optional second part - not ending with '/'. 可选的第二部分-不以'/'结尾。

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.

相关问题 正则表达式,用于匹配以模式开头但不以模式结尾的字符串 - Regex for matching a string starting with a pattern and not ending with a pattern 正则表达式匹配以特定数字开头并以分号结尾的字符串 - Regex to match string starting with particular number and ending in semicolon 自定义Java正则表达式:匹配以开头和结尾 - Custom Java Regex: Match starting with and ending with 匹配以(regex)java结尾的字符串 - Match String ending with (regex) java Java正则表达式选择字符串中的开始和结束引号 - Java Regex to select starting and ending quotes in a string 正则表达式匹配以constatant开头的字符串 - Regex to match a string starting with constatant 匹配模式的短语的字符串正则表达式 - String Regex for Phrases That Match a Pattern java regex:匹配输入,以非数字或空字符串开头,后跟特定模式 - java regex: match input starting with non-number or empty string followed by specific pattern 从字符串中删除所有以char'['开始并以char']'结尾的正则表达式实例 - Deleting all regex instances starting with char '[' and ending with char ']' from a String 如何为以3个数字或连字符结尾的字符串编写正则表达式模式? - How do i write a regex pattern for a string ending with 3 numbers or a hypen?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM