Php PCRE模式数字正则表达式后跟任意数字并向前斜杠没有以数字结尾的双斜杠?
到目前为止,我有以下几点:Php PCRE模式数字正则表达式后跟任意数字并向前斜杠没有以数字结尾的双斜杠?,php,regex,Php,Regex,到目前为止,我有以下几点: '#^[0-9]([0-9]|/)*$[0-9]#' 我使用了#作为分隔符,因为模式中使用了前斜杠 它工作不正常,但是,它需要以数字开头,包含数字和斜杠(无双斜杠),以数字结尾。我的解决方案: '#^[0-9]+(/[0-9]+)*$#' 编辑 如果必须至少存在一个斜杠: '#^[0-9]+(/[0-9]+)+$#' 或者使用非收集括号和\d代替[0-9]: '#^\d+(?:/\d+)*$#' 我忘了如何更改分隔符。对于某些命令/语言,您必须像这样启动Del
'#^[0-9]([0-9]|/)*$[0-9]#'
我使用了#
作为分隔符,因为模式中使用了前斜杠
它工作不正常,但是,它需要以数字开头,包含数字和斜杠(无双斜杠),以数字结尾。我的解决方案:
'#^[0-9]+(/[0-9]+)*$#'
编辑
如果必须至少存在一个斜杠:
'#^[0-9]+(/[0-9]+)+$#'
或者使用非收集括号和\d
代替[0-9]
:
'#^\d+(?:/\d+)*$#'
我忘了如何更改分隔符。对于某些命令/语言,您必须像这样启动Delimier \#开始时使用#作为分隔符。你可能不是这样 我可能应该先查一下我的简历。但这里有一个诚实的打击
'#^[0-9][0-9/[^(//)]]+[0-9]$#' //greedy
'#^[0-9][0-9/[^(//)]]+?[0-9]$#' //non-greedy
您可以使用这个简单的正则表达式(显示哪些字符串匹配或失败): 代码示例
$regex = "~^\d(?:(?!//)[\d/])+\d$~";
if(preg_match($regex,$string,$m)) echo $m[0];
解释正则表达式
^ # the beginning of the string
\d # digits (0-9)
(?: # group, but do not capture (1 or more times
# (matching the most amount possible)):
(?! # look ahead to see if there is not:
// # '//'
) # end of look-ahead
[\d/] # any character of: digits (0-9), '/'
)+ # end of grouping
\d # digits (0-9)
$ # before an optional \n, and the end of the
# string
您应该使用如下内容:
%^\d+(?:/\d+)+$%usD
说明:
% # beginning of the pattern
^ # beginning of the string
\d+ # it starts with at least one digit
(?: # beginning of a non-capturing group which contains
/ # a single slash
\d+ # followed by at least one digit, so it will never match double slashes
) # end of non-capturing group
+ # the non-capturing group should match once or more
$ # end of the string
% # end of the pattern
u # unicode string
s # the "." matches all characters including "\n"
D # the "$" matches the end of the string and not "\n" (end of the line)
快速帮助。我正在研究一个完整的答案,但要以数字结尾,请将$放在最后一个#之前,如[0-9]$#'您能提供一些示例输入和想要的输出吗?
12//3
应该返回什么?对于不需要[^]的字符(将字符放在胡萝卜后面)。例如,这意味着不是字母w:[^w],它是“任意数字和正斜杠”或“它需要以数字开头并包含数字和斜杠”???是否允许它不包含斜杠?是否允许它包含一个数字?\d
会使它看起来更好。哦,的确如此。我在许多环境中使用正则表达式,但并非所有环境都理解\d,因此我习惯于使用[0-9]相反,.\d不会使它更有效。@tzunghaor:我不确定您是否排除了双斜杠的可能性:/
每个斜杠后面必须至少有一个数字。我甚至尝试过一些简单的双斜杠。基于问题的描述,而不是标题。我的语法可能不正确,但这个概念符合问题lem描述最好。提示很好。非常好。但是,他的模式是查找/
,网站似乎默认将这些视为分隔符。知道如何更改分隔符吗?@AnthonyRutledge您可以在我的代码示例中看到分隔符是~
@Downvoter为什么是downvote?当问题出现时,如何将任何人的答案投上和描述不一致?
% # beginning of the pattern
^ # beginning of the string
\d+ # it starts with at least one digit
(?: # beginning of a non-capturing group which contains
/ # a single slash
\d+ # followed by at least one digit, so it will never match double slashes
) # end of non-capturing group
+ # the non-capturing group should match once or more
$ # end of the string
% # end of the pattern
u # unicode string
s # the "." matches all characters including "\n"
D # the "$" matches the end of the string and not "\n" (end of the line)