简体   繁体   English

PHP Regex IF THEN模式

[英]PHP Regex IF THEN pattern

I'm new to writing Regex patterns and I'm struggling to understand why the following line doesn't work. 我是刚开始编写Regex模式的新手,并且正努力理解为什么以下行不起作用。

/^(£)?[0-9]+(?(?=\.[0-9]{2}){0,1}(p)?|$)/

Note: I'm writing this in PHP 注意:我是用PHP编写的

I want the code to find £3.10p, but not £3p. 我希望代码查找3.10英镑,而不是3英镑。 Essentially, the letter 'p' can't be allowed unless it is preceded with a decimal point and 2 digits. 本质上,除非带小数点和2位数字,否则不允许使用字母'p'。

EDIT: To clarify, the letter p can be used at the end of the string, however if the string contains a £ and/or a decimal point, the p must be preceded by the point and 2 digits. 编辑:为明确起见,字母p可以在字符串的末尾使用,但是,如果字符串包含£和/或小数点,则p必须以点和2位数字开头。

More examples of valid inputs: £3.50 350 £350 234p 有效输入的更多示例:£3.50 350£350 234p

Invalid input: £2p 无效输入:£2p

Could someone please fix this and explain where I've gone wrong here? 有人可以解决这个问题,并解释我在这里出了什么问题吗?

Thanks 谢谢

If 0.50p is allowed, then you can do it like this: 如果允许0.50p,则可以这样:

^((£?[0-9]+)(?!p)|([0-9]+p?))?(?<!p)(\.[0-9]{2})?p?$

Regex saved with all your examples here: https://regex101.com/r/rE1bT9/3 正则表达式保存了您所有的示例: https//regex101.com/r/rE1bT9/3

Try this: /^(?(?=£)(£\\d+\\.\\d{2}p?|£\\d+)|\\d+p?)$/ 试试这个:/ /^(?(?=£)(£\\d+\\.\\d{2}p?|£\\d+)|\\d+p?)$/

You can test it here: https://regex101.com/r/mG8kR0/1 您可以在这里进行测试: https//regex101.com/r/mG8kR0/1

It is unclear how your valid sample "234p" matches your rule "p is allowed if there are at least two digits and a point". 尚不清楚您的有效样本“ 234p”如何与规则“如果至少有两位数和一个点允许p”匹配。 However, in your question you are using positive lookahead, this seems an overhead here. 但是,在您的问题中,您正在使用正向超前,这似乎是开销。

Your rule for p may be written as: (\\.[0-9]{2}p?) 您的p规则可以写为: (\\.[0-9]{2}p?)

So over all, you just need: /^(£)?[0-9]+(\\.[0-9]{2}p?)$/ 因此,总的来说,您只需要:/ /^(£)?[0-9]+(\\.[0-9]{2}p?)$/

And if you allow "234p" also, just make the period optional: /^(£)?[0-9]+(\\.?[0-9]{2}p?)$/ 并且如果您还允许使用“ 234p”,则只需将句点/^(£)?[0-9]+(\\.?[0-9]{2}p?)$/ :/ /^(£)?[0-9]+(\\.?[0-9]{2}p?)$/

Try it out here: http://www.regexr.com/ 在这里尝试: http : //www.regexr.com/

The latter regex gives positive feedback to all your valid samples, and it denies the invalid input. 后一个正则表达式为所有有效样本提供正反馈,并且拒绝无效输入。 It is unclear what should happen if there are only two digits, and if it is important to catch some pieces, there should be more brackets. 目前尚不清楚如果只有两位数字会发生什么,并且如果重要的是抓住一些数字,那么应该有更多的括号。

怎么样:

/^(?:£?[0-9]+(?:\.[0-9]{2})?|[0-9]+p?)$)/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM