java 正则表达式检查字符串是否以特定字符开头和结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15634449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx to check if a string starts and end with a particular character
提问by Saju
I need a regular expression that checks if the string starts and end with a special character like -
我需要一个正则表达式来检查字符串是否以特殊字符开头和结尾,例如 -
%ASDF%
"ASDF"
@ASDF@
回答by Naveed S
The following regex matches strings that begin and end with the same character:
以下正则表达式匹配以相同字符开头和结尾的字符串:
(.).*
.
stands for any character and enclosing is for marking a capture group so that it can be backreferenced.
.
代表任何字符,封闭用于标记捕获组,以便它可以被反向引用。
.*
matches zero or more characters.
.*
匹配零个或多个字符。
\1
backreferences the first capture group (i.e. the first character)
\1
反向引用第一个捕获组(即第一个字符)
So it matches aba, #ee#, eeetc. If you require at least one character between starting and ending characters, replace the *
with +
.
所以它匹配ABA,#EE# ,EE等,如果你需要开始和结束字符之间至少有一个字符,替换*
用+
。
回答by Lefteris E
^((%.+%)|(".+")|(@.+@))$
^
means start of the line$
means end of the line|
means or.
means any character+
means repeated 1 or more times
^
意味着行的开始$
表示行尾|
手段或.
表示任何字符+
表示重复 1 次或多次