简体   繁体   中英

Determine a common regex pattern from a list of strings in Python

I have a list of different strings. I would like to find out a common regex expression (if any) for that list using Python.
For example, my list contains the following strings:

myList = ['This is first string', 'This is 2nd String', 'This is string 3', 'This is a final string']

Then I would like to programmatically determine if there is a regex expression which will match all the strings in the list. For instance, here the expression is something like 'This is *'. Will it be possible to do this programmatically?

use operator | to join together each literal match. place inside ^(...)$

pattern = "^(" + "|".join(re.escape(item) for item in myStrings) + ")$"

它很简单, /\\'This is ([a-zA-Z0-9])*\\'/ /This is ([a-zA-Z0-9])*/不需要引号/\\'This is ([a-zA-Z0-9])+\\'/ - 任何东西都必须在 This is 之后。

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