正则表达式匹配第一个和最后一个字符 [英] Regular Expression to match first and last character

查看:1184
本文介绍了正则表达式匹配第一个和最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我知道这是匹配第一个字符:

  / ^ [az] / i 

但是如何才能检查最后一个字符?这是:

  / ^ [az] [az] $ / i 
pre>

不工作。我怀疑两个条款之间应该有什么,但我不知道什么!



任何帮助将不胜感激。

解决方案

下面的正则表达式将匹配以alpha字符开头和结尾的字符串。

  / ^ [az]。* [az] $ / igm 

a 字符串也以字母开头和结尾,对吧?那么你必须使用下面的正则表达式。

  / ^ [az](。* [az])?$ / igm 

演示



说明:

 code> ^#表示开始一行。 
[a-z]#alphabatic character。
。*#任意字符0次以上。
[a-z]#alphabatic character。
$#一行结束。
我#不区分大小写的匹配。
g#global。
m#multiline


I'm trying to use regex to check that the first and last characters in a string are alpha characters between 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.

解决方案

The below regex will match the strings that starts and ends with alpha character.

/^[a-z].*[a-z]$/igm

a string also starts and endswith alpha character , right? Then you have to use the below regex.

/^[a-z](.*[a-z])?$/igm

DEMO

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

这篇关于正则表达式匹配第一个和最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆