I'm trying to use regex to check that the first and last characters in a string are alpha characters between a-z.
我正在尝试使用regex检查字符串中的第一个和最后一个字符是否是a-z之间的字符。
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!
不工作。我怀疑这两个条款之间应该有什么东西,但我不知道是什么!
Any help would be much appreciated.
如有任何帮助,我们将不胜感激。
2 个解决方案
#1
18
The below regex will match the strings that starts and ends with alpha character.
下面的regex将匹配以字符开头和结尾的字符串。
/^[a-z].*[a-z]$/igm
a
string also starts and endswith alpha character , right? Then you have to use the below regex.
字符串也开始和结束字符,对吧?然后您必须使用下面的regex。
/^[a-z](.*[a-z])?$/igm
演示
Explanation:
解释:
^ # Represents begining of a line.
[a-z] # alphabatic character.
.* # Any character 0 or more times.
[a-z] # alphabatic character.
$ # End of a line.
i # case-insensitive match.
g # global.
m # multiline
#2
4
You can do it as follows to check for the first and last characters and then anything in between:
您可以按照以下步骤检查第一个和最后一个字符,然后检查中间的任何字符:
/^[a-z].*[a-z]$/im
演示
#1
18
The below regex will match the strings that starts and ends with alpha character.
下面的regex将匹配以字符开头和结尾的字符串。
/^[a-z].*[a-z]$/igm
a
string also starts and endswith alpha character , right? Then you have to use the below regex.
字符串也开始和结束字符,对吧?然后您必须使用下面的regex。
/^[a-z](.*[a-z])?$/igm
演示
Explanation:
解释:
^ # Represents begining of a line.
[a-z] # alphabatic character.
.* # Any character 0 or more times.
[a-z] # alphabatic character.
$ # End of a line.
i # case-insensitive match.
g # global.
m # multiline
#2
4
You can do it as follows to check for the first and last characters and then anything in between:
您可以按照以下步骤检查第一个和最后一个字符,然后检查中间的任何字符:
/^[a-z].*[a-z]$/im
演示