用语言标记开头

时间:2018-11-05 09:01:53

标签: python

我有以下说明

In [362]: !cat data.md                                                                                            
**File Permission Related Commands**

These commands are used to change permissions of the files

```
72. chmod octal file-name                : Changes the permissions of file to octal
    chmod 777 /data/test.c                   : Sets rwx permission for owner , group and others
```

**Network Related Commands**

These commands are used to view and edit network configurations related aspects of the system

```
75. ifconfig -a        : Displays all network interface and set ip address

我想用```python```标记``````,
所以我应该将开头```更改为```python

In [363]: f = open("data.md", "r+")                                                                               

In [364]: data = f.read()                                                                                         

In [365]: import re                                                                                               

In [366]: re.sub(r"^(```)", "```bash", data)                                                                      
Out[366]: '**File Permission Related Commands**\n\nThese commands are used to change permissions of the files\n\n```\n72. chmod octal file-name      \t\t     : Changes the permissions of file to octal\n    chmod 777 /data/test.c

但是,什么都没有改变。

我怎么完成它?

1 个答案:

答案 0 :(得分:2)

^在正常模式下匹配字符串的开头。要使其与行的开头匹配,请将re.MULTILINE传递到re.sub

re.sub(r"^(```)", "```bash", data, flags=re.MULTILINE)     

编辑:只正确替换开头的配对对

re.sub(r'```([^`]+)```', r'```bash\1```', data) 
# don't actually need ^ and MULTILINE in your example