When is it best to use Regular Expressions over basic string splitting / substring'ing?

前端 未结 7 1636
旧巷少年郎
旧巷少年郎 2020-12-01 12:46

It seems that the choice to use string parsing vs. regular expressions comes up on a regular basis for me anytime a situation arises that I need part of a string, informatio

7条回答
  •  爱一瞬间的悲伤
    2020-12-01 12:57

    The regex can be

    • easier to understand
    • express more clearly the intent
    • much shorter
    • easier to change/adapt

    In some situations all of those advantages would be achieved by using a regex, in others only some are achieved (the regex is not really easy to understand for example) and in yet other situations the regex is harder to understand, obfuscates the intent, longer and hard to change.

    The more of those (and possibly other) advantages I gain from the regex, the more likely I am to use them.

    Possible rule of thumb: if understanding the regex would take minutes for someone who is somewhat familiar with regular expressions, then you don't want to use it (unless the "normal" code is even more convoluted ;-).

    Hm ... still no simple rule-of-thumb, sorry.

提交回复
热议问题