简体   繁体   English

可以使用正则表达式计算此函数的反函数吗?

[英]Can the inverse of this function be computed using regular expressions?

I have a function that converts a class name (in Spanish!) from singular form to plural form: 我有一个函数将类名(西班牙语!)从单数形式转换为复数形式:

function pluralize($element) {
    return preg_replace('/^([A-Za-z][a-z]*)([A-Z]|$)/', '\1s\2', $element);
}

Now I would like to define the inverse of this function. 现在我想定义这个函数的逆。 Is the following function valid? 以下功能有效吗?

function singularize($plural) {
    return preg_replace('/^([A-Za-z][a-z]*)(s)([A-Z]|$)/', '\1\3', $element);
}

It should work fine, but you don't need parentheses around the s in the second pattern. 它应该工作正常,但在第二种模式中你不需要围绕s的括号。 You also need to keep in mind that if you have multiple s, neither pattern is going to care about that. 你还需要记住,如果你有多个s,那么这两种模式都不会关心它。 So the first pattern will change ClassX to ClasssX and the second will change it back to ClassX. 因此,第一个模式将ClassX更改为ClasssX,第二个模式将其更改为ClassX。 Just something to keep in mind. 请记住一些事情。

As a rule, only if 's' is excluded from the [az]* position 通常,只有's'被排除在[az] *位置之外
when creating the class name. 在创建类名时。

That would mean [az]* needs to exclude 's'. 这意味着[az] *需要排除's'。 Like [a-rt-z]* [a-rt-z]*
Then these might work. 然后这些可能会奏效。

/^([A-Za-z][a-rt-z]*) ([AZ]|$)/x
/^([A-Za-z][a-rt-z]*)(s)([AZ]|$)/x

edit - otherwise (with what you have), you would have to keep track of what state each classname is in. ie: if it hasn't been pluralized, it can't be singularized, otherwise an extra 's' might be stripped from the original class name. 编辑 - 否则(用你拥有的东西),你必须跟踪每个类名所处的状态。即:如果它没有被复数,它就不能被单一化,否则一个额外的's'可能被剥夺从原来的班级名称。

The regex's above don't need to maintain state, but they are limited in form. 上面的正则表达式不需要维持状态,但它们的形式有限。
It might be better to add a distinguishing character into the class to differentiate it from singular/plural state. 最好在类中添加一个区别字符,以区别于单数/复数状态。 Maybe an underscore if its supported. 如果得到支持,也许是一个下划线。 Otherwise there will be no control or other identifiable marking to tell which is which. 否则将没有控制或其他可识别的标记来说明哪个是哪个。

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

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