Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式:替换子字符串的多种可能性_Python_Regex_String_Replace_Str Replace - Fatal编程技术网

Python正则表达式:替换子字符串的多种可能性

Python正则表达式:替换子字符串的多种可能性,python,regex,string,replace,str-replace,Python,Regex,String,Replace,Str Replace,我想移除指示灯,如图1所示。在字符串标题中,其中标题可以是: 我试过caption=re.subr'figure 1:| fig 1 | figure 1-',caption,flags=re.IGNORECASE,但看起来很混乱:我真的需要手动列出所有的可能性吗?是否有任何元素重新编码以匹配所有元素 非常感谢 您可以使用可选部分来匹配ure,并使用可选字符类来匹配:;或- 如果要匹配除1以外的其他数字,请使用\d+ \bfig匹配图前面有单词边界 \.? 匹配一个可选的点 ?:你呢?可选匹配u

我想移除指示灯,如图1所示。在字符串标题中,其中标题可以是:

我试过caption=re.subr'figure 1:| fig 1 | figure 1-',caption,flags=re.IGNORECASE,但看起来很混乱:我真的需要手动列出所有的可能性吗?是否有任何元素重新编码以匹配所有元素


非常感谢

您可以使用可选部分来匹配ure,并使用可选字符类来匹配:;或-

如果要匹配除1以外的其他数字,请使用\d+

\bfig匹配图前面有单词边界 \.? 匹配一个可选的点 ?:你呢?可选匹配ure 1匹配空格和1 [^\S\r\n]*匹配0+次出现的空白字符,换行符除外 [:.;–-]? (可选)匹配字符类中列出的任何字符 |

还匹配字符类后的空白的示例代码:

caption = re.sub(r'\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?[^\S\r\n]', '', caption, flags=re.IGNORECASE)

您可以将模式缩短为r'\bfig?:\.\ure?\s+1?:\s*[-:]Thx!但有一个有趣的例子:```caption=FIGURE 1-Travel CP net re.subr'\bfig\:你呢?1[^\S\r\n]*[:.;-]?[^\S\r\n]',标题,标志=re.IGNORECASE Travel CP net caption=图1–系统图re.subr'\bfig\:ure?1[^\S\r\n]*[:.;-]?[^\S\r\n]',标题,flags=re.IGNORECASE–系统图“``为什么?
\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?
caption = re.sub(r'\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?[^\S\r\n]', '', caption, flags=re.IGNORECASE)