简体   繁体   中英

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. You also need to keep in mind that if you have multiple s, neither pattern is going to care about that. So the first pattern will change ClassX to ClasssX and the second will change it back to ClassX. Just something to keep in mind.

As a rule, only if 's' is excluded from the [az]* position
when creating the class name.

That would mean [az]* needs to exclude 's'. Like [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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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