[英]Regular expression to match first and last character
I'm trying to use regex to check that the first and last characters in a string are alpha characters between az.我正在尝试使用正则表达式来检查字符串中的第一个和最后一个字符是否是 az 之间的字母字符。
I know this matches the first character:我知道这与第一个字符匹配:
/^[a-z]/i
But how do I then check for the last character as well?但是我又该如何检查最后一个字符呢?
This:这个:
/^[a-z][a-z]$/i
does not work.不起作用。 And I suspect there should be something in between the two clauses, but I don't know what!
我怀疑这两个条款之间应该有什么东西,但我不知道是什么!
The below regex will match the strings that start and end with an alpha character. 以下正则表达式将匹配以字母开头和结尾的字符串。
/^[a-z].*[a-z]$/igm
The a
string also starts and ends with an alpha character, right? a
字符串也以alpha字符开头和结尾,对吧? Then you have to use the below regex. 然后你必须使用下面的正则表达式。
/^[a-z](.*[a-z])?$/igm
Explanation: 说明:
^ # Represents beginning of a line.
[a-z] # Alphabetic character.
.* # Any character 0 or more times.
[a-z] # Alphabetic character.
$ # End of a line.
i # Case-insensitive match.
g # Global.
m # Multiline
var str = "Regular";
//following code should return true as first and last characters are same
var re = /(^[a-zA-Z])(.*)\1$/gi;
console.log(re.test(str); //true
Match 1 : Regular
Group 1 : (^[a-zA-Z]) = R
Group 2 : (.*) = egula
\1$ : Match the same what is caught in group 1 at the end = r
You can use this:你可以使用这个:
/^.|.$/gim
it match with first and last character它与第一个和最后一个字符匹配
put characters in groups like ([group1])([group2])\1.将字符分组,如 ([group1])([group2])\1。 The \1 says the last group matches group 1.
\1 表示最后一组匹配组 1。
([a-z])([someRegex])\1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.