Find what part of a string do not match with regular expression python
Question: In order to see if a filename is correctly named (using re) I use the
following regular expression pattern :

    
    
    *^S_hc_[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}_[0-9]{4,4}-[0-9]{1,3}T[0-9]{6,6}\.xml$"*
    

Here is a correct file name : `*S_hc_1.2.3_2014-213T123121.xml*`

Here is an incorrect file name :
`*S_hc_1.2.IncorrectName_2014-213T123121.xml*`

I would like to know if a simple way to retrieve the part of the file which to
do not match exits.

In the end, an error message would display :

    
    
    Error, incorrect file name, the part 'IncorrectName' does not match with expected name. 
    


Answer: You can use `re.split` and a generator expression within
[`next`](https://docs.python.org/2/library/functions.html#next) but you also
need to check the structure of your string that match waht you want, you can
do it with following re.match :

    
    
    re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2)
    

And in code:

    
    
    >>> import re
    >>> s2 ='S_hc_1.2.IncorrectName_2014-213T123121.xml'
    >>> s1
    'S_hc_1.2.3_2014-213T123121.xml'
    #with s1
    >>> next((i for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s1) if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2)),None)
    #with s2
    >>> next((i for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s2) if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2)),None)
    'IncorrectName'
    

All you need is to use pip (`|`) between unique part of your regex
patterns,then the `split` function will split your string based on one of that
patterns.

And the part that doesn't match with one of your pattern will not be split and
you can find it with looping over your split text!

> **next(iterator[, default])**
>
> Retrieve the next item from the iterator by calling its next() method. If
> default is given, it is returned if the iterator is exhausted, otherwise
> StopIteration is raised.

If you want in several line :

    
    
    >>> for i in re.split(r'^S_hc_|[0-9]{1,2}\.|[0-9]{1,2}_|_|[0-9]{4,4}|-|[0-9]{1,3}T[0-9]{6}|\.|xml$',s2):
    ...   if i and re.match(r"^S_hc_(.*)\.(.*)\.(.*)_(.*)-(.*)\.xml$",s2):
    ...        print i
    ... 
    IncorrectName
    

