Programmatically derive a regular expression from a string

前端 未结 4 1815
北恋
北恋 2021-01-02 23:14

I would like to input a string and return a regular expression that can be used to describe the string\'s structure. The regex will be used to find more strings of the same

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 23:25

    The trivial answer, and probably not what you want, is: return the input string (with regex special characters escaped). That is always a regular expression that matches the string.

    If you wish certain structures to be identified, you have to provide more information about the kind of structures you wish to have identified. Without that information, the problem is stated in an ambiguous way and there are many possible solutions. For instance, the input string 'aba' can be described as

    'aba'

    'aba*'

    'aba?'

    'ab\w'

    '\w{3}'

    '(.)b\1'

    etc.

提交回复
热议问题