正则表达式匹配特定字符的确切出现次数 [英] Regular expression to match an exact number of occurrence for a certain character
问题描述
我正在尝试检查字符串是否出现了一定数量的字符.
I'm trying to check if a string has a certain number of occurrence of a character.
示例:
$string = '123~456~789~000';
我想验证这个字符串是否正好有 3 个字符 ~
的实例.
I want to verify if this string has exactly 3 instances of the character ~
.
使用正则表达式可以吗?
Is that possible using regular expressions?
推荐答案
由于单个字符在技术上是一个子字符串,任务是计算它出现的次数,我认为最有效的方法是使用特殊的 PHP 函数- substr_count:
As single character is technically a substring, and the task is to count the number of its occurences, I suppose the most efficient approach lies in using a special PHP function - substr_count:
$string = '123~456~789~000';
if (substr_count($string, '~') === 3) {
// string is valid
}
显然,如果您需要计算模式匹配的数量,这种方法将不起作用(例如,虽然您可以使用 substr_count
计算字符串中0"的数量,但您最好使用 preg_match_all
计算数字).
Obviously, this approach won't work if you need to count the number of pattern matches (for example, while you can count the number of '0' in your string with substr_count
, you better use preg_match_all
to count digits).
然而,对于这个特定问题,它总体上应该更快,因为 substr_count
针对一个特定目标进行了优化 - 计算子字符串 - 当 preg_match_all
更适用于通用方面时.)
Yet for this specific question it should be faster overall, as substr_count
is optimized for one specific goal - count substrings - when preg_match_all
is more on the universal side. )
这篇关于正则表达式匹配特定字符的确切出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!