以编程方式从字符串派生正则表达式 [英] Programmatically derive a regular expression from a string

查看:88
本文介绍了以编程方式从字符串派生正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入一个字符串并返回一个可用于描述字符串结构的正则表达式.正则表达式将用于查找与第一个相同结构的更多字符串.

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 structure as the first.

这是故意模棱两可的,因为我肯定会错过SO社区中某人会抓到的情况.

This is intentionally ambiguous because I will certainly miss a case that someone in the SO community will catch.

请发布所有可能的方法.

Please post any and all possible ways to do this.

推荐答案

最简单的答案(可能不是您想要的)是:返回输入字符串(使用正则表达式特殊字符转义).这始终是与字符串匹配的正则表达式.

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.

如果您希望标识某些结构,则必须提供有关希望标识的结构类型的更多信息.没有这些信息,问题就被模棱两可,并且存在许多可能的解决方案.例如,输入字符串'aba'可以描述为

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'

这篇关于以编程方式从字符串派生正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆