https://docs.python.org/3.12/library/re.html#module-re

. 匹配任何一个字符,不包括换行符
* 匹配前一个规则的0到任意多次
+ 匹配前一个规则的1到任意多次
? 匹配前一个规则的0或1次
(…) 括号做整体
[…] 中括号内任意一个,此时. * ?失去规则效应,就是普通的字符

sub比较高级的使用方式,就是传入函数,对需要替换的字符串做进一步的处置,一般replace只能将现有的字符串替换,不能对被替换的字符串操作,但实际需要对被替换的字符串操作拿到替换的字符串

像:#include<—>,需要替换所有的头include,注释掉,替换的字符串 和 被替换的字符串是紧密相关的

  • 替换的字符串:#include<—>或者 #include “”
  • 被替换的字符串 // #include<—>或者 // #include “”

需要就需要使用re.sub,传入函数修改字符串并替换

像匹配字符串 #include<—>,或者 #include “—”,然后注释掉,在前面加上 //,此时就可以用re.sub来做

文本是:

#include<iostream>
#include "stdio.h"
#include "stdlib.h"
#include<vector>
#include<string>
#include<unordered_map>
#include<map>
#include<set>

class Solution {// 注释 #include<iostream> string convert(string s, int numRows)
public:
    string convert(string s, int numRows) {
        string ret, tmp[numRows];
        int i = 0;
        vector<int> tr;
        int k = tr[0];
        while(i < s.length()) {
            for(int k = 0; k < numRows && i < s.length(); k++) {
                tmp[k] += s[i++];
            }
            for(int k = numRows-2; k > 0 && i < s.length(); k--) {
                tmp[k] += s[i++];
            }
        }

替换的code,下面的replace_sub函数就是重点的

import re
    string = \
'''
#include<iostream>
#include "stdio.h"
#include "stdlib.h"
#include "own.hpp"
#include<vector>
#include<string>
#include<unordered_map>
#include<map>
#include<set>

class Solution {// 注释 #include<iostream> string convert(string s, int numRows)
public:
    string convert(string s, int numRows) {
        string ret, tmp[numRows];
        int i = 0;
        vector<int> tr;
        int k = tr[0];
        while(i < s.length()) {
            for(int k = 0; k < numRows && i < s.length(); k++) {
                tmp[k] += s[i++];
            }
            for(int k = numRows-2; k > 0 && i < s.length(); k--) {
                tmp[k] += s[i++];
            }
        }
'''

    def replace_sub(txt):
        inp = txt[0]
        return '// ' + inp
    
    precode = re.sub('#include *[<\"\']\w*.?\w*[>\"\']', replace_sub, string)

替换以后的结果是:

// #include<iostream>
// #include "stdio.h"
// #include "stdlib.h"
// #include "own.hpp"
// #include<vector>
// #include<string>
// #include<unordered_map>
// #include<map>
// #include<set>

class Solution {// 注释 // #include<iostream> string convert(string s, int numRows)
public:
    string convert(string s, int numRows) {
        string ret, tmp[numRows];
        int i = 0;
        vector<int> tr;
        int k = tr[0];
        while(i < s.length()) {
            for(int k = 0; k < numRows && i < s.length(); k++) {
                tmp[k] += s[i++];
            }
            for(int k = numRows-2; k > 0 && i < s.length(); k--) {
                tmp[k] += s[i++];
            }
        }
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐