regular expressions terthen one or more word characters optionally followed by periodwith the whole of this second part itself matching zero or more times when we use alternation (|with two or more alternatives capturingwe don' know which alternative matchedso we don' know which capture group to retrieve the captured text from we can of course iterate over all the groups to find the nonempty onebut quite often in this situation the match object' lastindex attribute can give us the number of the group we want we will look at one last example to illustrate this and to give us little bit more regex practice suppose we want to find out what encoding an htmlxmlor python file is using we could open the file in binary modeand readsaythe first bytes into bytes object we could then close the filelook for an encoding in the bytesand reopen the file in text mode using the encoding we found or using fallback encoding (such as utf- the regex engine expects regexes to be supplied as stringsbut the text the regex is applied to can be strbytesor bytearray objectand when bytes or bytearray objects are usedall the functions and methods return bytes instead of stringsand the re ascii flag is implicitly switched on for html files the encoding is normally specified in tag (if specified at all)for example<meta http-equiv='content-typecontent='text/htmlcharset=iso- - '/xml files are utf- by defaultbut this can be overriddenfor examplepython files are also utf- by defaultbut again this can be overridden by including line such as encodinglatin or -*codinglatin -*immediately after the shebang line here is how we would find the encodingassuming that the variable binary is bytes object containing the first bytes of an htmlxmlor python filematch re search( """(?<![-\ ]# (?:(?:en)?coding|charset# (?:=(["'])?([-\ ]+)(?( )\ # |:\ *([-\ ]+))""encode("utf ")binaryre ignorecase|re verboseencoding match group(match lastindexif match else "utf to search bytes object we must specify pattern that is also bytes object in this case we want the convenience of using raw stringso we use one and convert it to bytes object as the re search(function' first argument conditional matching the first part of the regex itself is lookbehind assertion that says that the match cannot be preceded by hyphen or word character the second part matches "encoding""coding"or "charsetand could have been written as (?:encoding|coding|charsetwe have made the third part span two lines to emphasise the fact that it has two alternating parts=(["'])?([-\ ]+)(?( )\