2019年4月3日 星期三

[ Python 常見問題 ] Matching any character including newlines in a Python re

Source From Here 
Question 
I want to use re.MULTILINE but NOT re.DOTALL, so that I can have a regex that includes both an "any character" wildcard and the normal . wildcard that doesn't match newlines. 

Is there a way to do this? What should I use to match any character in those instances that I want to include newlines? 

How-To 
To match a newline, or "any symbol" without re.S/re.DOTALL, you may use any of the following: 
  1. [\s\S]  
  2. [\w\W]  
  3. [\d\D]  
The main idea is that the opposite shorthand classes inside a character class match any symbol there is in the input string. 

Comparing it to (.|\s) and other variations with alternation, the character class solution is much more efficient as it involves much less backtracking (when used with a * or + quantifier). Compare the small example: it takes (?:.|\n)+ 45 steps to complete, and it takes [\s\S]+ just 2 steps. 

Let's test this solution a little bit: 
>>> import re
>>> astr = '<html><!--This is comment.\nSecond line --></html>'
>>> re.sub('<!--.*?-->', '', astr) # Won't work in multiple line
'<html><!--This is comment.\nSecond line --></html>'
>>> re.sub('<!--.*?-->', '', '<html><!--single line--></html>') # Only work in single lin
'<html≷</html≷'

>>> re.sub('<!--[\s\S]*?-->', '', astr) # Work for both single/multiple lines
'<html>&t;/html>'
>>> re.sub('<!--[\s\S]*?-->', '', '<html><!--single line--></html>')
'<html></html>'


Supplement 
String services : re — Regular expression operations

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...