LoginSignup
2
1

More than 5 years have passed since last update.

Python > regex > 書式文字列("[Text:"と"]")だけを置換する

Last updated at Posted at 2018-05-28
動作環境
ideone (Python 3.5)

処理

[Tex:Z_c = \frac{1}{2 \pi f C}]

を下記のように置換したい (Hatena DiaryからMarkdown形式への置換)。


```math
Tex:Z_c = \frac{1}{2 \pi f C}
```

code v0.1

import re

intxt = "[Tex:Z_c = \frac{1}{2 \pi f C}]"
# 以下に置き換える
#```math
#Tex:Z_c = \frac{1}{2 \pi f C}
#```

print(intxt)

wrk = re.sub('\[Tex', '```math```', intxt)
print(wrk)

run
[Tex:Z_c = rac{1}{2 \pi f C}]
```math```:Z_c = rac{1}{2 \pi f C}]

右の"]"の扱いをどうするか思案中。

code v0.2

import re

intxt = r"[Tex:Z_c = \frac{1}{2 \pi f C}]"
# 以下に置き換える
#```math
#Tex:Z_c = \frac{1}{2 \pi f C}
#```

def conv_tex(intxt):
    if r"[Tex:" in intxt:
        wrk = re.sub('\[Tex:', r'```math\r\n', intxt)
        wrk = re.sub(r']', r'\r\n```', wrk)
        return wrk
    return intxt

print(intxt)
res = conv_tex(intxt)
print(res)


[Tex:Z_c = \frac{1}{2 \pi f C}]
```math
Z_c = \frac{1}{2 \pi f C}
```

もうちょっと考えることはありそう。

code v0.3

  • 複数行への対応
  • Tex表記以外の置換がおきないように対応

import re


def conv_tex(intxt):
    res = ""
    for elem in intxt.split('\n'):
        if len(res) > 0:
            res += '\r\n'

        if r"[Tex:" in elem:
            wrk = re.sub('\[Tex:', r'```math\r\n', elem)
            wrk = re.sub(r']', r'\r\n```', wrk)
            res += wrk
        else:
            res += elem
    return res

IN_TEXTXT1 = r"[Tex:Z_c = \frac{1}{2 \pi f C}]"
# 以下に置き換える
# ```math
# Tex:Z_c = \frac{1}{2 \pi f C}
# ```

# dummy text
IN_DMYTXT1 = '[[[AAA]]]'

intxt = IN_TEXTXT1 + '\r\n' + IN_TEXTXT1
intxt += '\r\n' + IN_DMYTXT1
print(intxt)
print('---')
res = conv_tex(intxt)
print(res)


[Tex:Z_c = \frac{1}{2 \pi f C}]
[Tex:Z_c = \frac{1}{2 \pi f C}]
[[[AAA]]]
---
```math
Z_c = \frac{1}{2 \pi f C}
```

```math
Z_c = \frac{1}{2 \pi f C}
```

[[[AAA]]]

これで使えるだろうか。

code v0.4

結局、複数行対応ではなく、1行単位の処理を使った。

はてなダイアリー to Markdown > v0.5 > Tex:表記対応
のcode v0.5のconv_tex()

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1