正则表达式匹配整个字符串 [英] Regular Expression matching for entire string

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

问题描述

我对php很陌生.我需要检查给定的字符串是否具有来自给定集合的字符,例如{a, b, c}.因此,我尝试使用正则表达式. "(abc)+"应该可以解决问题.

I'm very new to php. I need to check whether a given string has characters from a given set say {a, b, c}. So, am trying regular expressions. "(abc)+" should do the trick.

但是,在查看preg_match及其相关功能的手册条目时,我注意到这些功能执行子字符串匹配,而不是使用正则表达式规则匹配整个字符串.

However, looking at the manual entries for preg_match and associated functions, I noticed that these functions perform sub-string matching instead of matching the entire string with the regex rule.

我敢肯定有一种简单的方法可以做到这一点.基本上,无论整个字符串是否符合规则,我都需要一个二进制答案.你们能帮我吗?

I'm sure there is a simple way to do this. Basically, I need a binary answer whether or not the entire string matches the rule. Could you guys help me out?

谢谢!

推荐答案

您可以使用方括号创建字符类.因此,[abc]将匹配类(括号)内的任何字符.

You can create your character class by using square brackets. So [abc] would match any of the characters inside the class (the brackets).

要获取其中的一系列,您需要一个量词.您已经使用了+表示一个或多个.如果您还希望允许使用空字符串,则可以使用*表示零个或多个.

To get a series of them, you need a quantifier. You already used the + that means one or more. If you also want to allow the empty string, you can use the * meaning zero or more.

为确保您要检查完整的字符串,需要使用锚点. ^将匹配字符串的开头,而$匹配字符串的结尾.

To ensure that you are checking the complete string you need anchors. ^ would match the start of the string and $ the end of the string.

^[abc]+$

如果整个字符串仅包含abc并且具有至少一个字符,则此正则表达式将匹配.

This regex would match if the complete string consists only of abc and has at least one character.

您可以在线测试正则表达式,例如在Regexr上.您可以在此处查看此正则表达式,当然可以对其进行修改.

You can test regexes online e.g. on Regexr. You can see this regex here and of course modify it.

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

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