lundi 8 octobre 2018

Matching a sequence of patterns

I have a sequence of patterns, and would like to match strings against those patterns and return the first group. I am coming from a scala background but I found myself needing to do the same thing in Python. Is there anyway to map and match a collection of patterns?

In scala it would look smth like that

 private val patterns = Stream(

Pattern.compile("([a-zA-Z\\d]{9}-[a-zA-Z\\d]{3})"),
Pattern.compile("([a-zA-Z\\d]{3}-[a-zA-Z\\d]{3}-\\d{4}-\\d{2})"),
Pattern.compile("([a-zA-Z\\d]{5}-[a-zA-Z\\d]{3}-\\d{4})"),
Pattern.compile("([a-zA-Z\\d]{5}-[a-zA-Z\\d]{3}-\\d{4})"),
Pattern.compile("([a-zA-Z\\d]{3}-[a-zA-Z\\d]{3}-\\d{4}-\\d{2})"),
Pattern.compile("([a-zA-Z\\d]{5}-[a-zA-Z\\d]{3}-\\d{4})"),
Pattern.compile("([a-zA-Z\\d!]{2,3}-[a-zA-Z\\d]{2,4}-[a-zA-Z\\d]{3,5}-[\\d]{1,2})"),
Pattern.compile("([a-zA-Z\\d]{3,6}-[a-zA-Z\\d]{3}-[\\d]{1,6})"),
Pattern.compile("([a-zA-Z\\d]{3,6}-[a-zA-Z\\d]{4}-[\\d]{1,6})")
)
patterns.map(_.matcher(sku)).find(_.matches()).map(_.group(1)

Aucun commentaire:

Enregistrer un commentaire