回答編集履歴

3

汎用的な正規表現を追加

2021/02/15 07:23

投稿

ppaul
ppaul

スコア24672

test CHANGED
@@ -8,8 +8,26 @@
8
8
 
9
9
  >>>
10
10
 
11
- >>> re.sub(r'(【テスト】.*)\n・', r'\1・', text)
11
+ >>> re.sub(r'(【テスト】[^\n]+)\n・', r'\1・', text)
12
12
 
13
13
  '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\n【テスト】micro\n-soft'
14
14
 
15
15
  ```
16
+
17
+ さらに一般的に二つの文字列を指定したい場合のためには、以下の形を覚えておくと便利です。
18
+
19
+
20
+
21
+ ```python
22
+
23
+ >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\n【テスト】micro\n-soft'
24
+
25
+ >>>
26
+
27
+ >>> re.sub(r'(【テスト】[^\n]+)(\n)(・)', r'\1\3', text)
28
+
29
+ '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\n【テスト】micro\n-soft'
30
+
31
+ ```
32
+
33
+ ()で囲まれたパターンが前から順に\1、\2、\3となるので、より汎用的に使えます。

2

例の間違いを修正

2021/02/15 07:23

投稿

ppaul
ppaul

スコア24672

test CHANGED
@@ -4,12 +4,12 @@
4
4
 
5
5
  ```python
6
6
 
7
- >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\ 【テスト】micro\n-soft'
7
+ >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\n【テスト】micro\n-soft'
8
8
 
9
9
  >>>
10
10
 
11
11
  >>> re.sub(r'(【テスト】.*)\n・', r'\1・', text)
12
12
 
13
- '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\【テスト】micro\n-soft'
13
+ '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\n【テスト】micro\n-soft'
14
14
 
15
15
  ```

1

例を追加

2021/02/15 02:12

投稿

ppaul
ppaul

スコア24672

test CHANGED
@@ -4,12 +4,12 @@
4
4
 
5
5
  ```python
6
6
 
7
- >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic'
7
+ >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\ 【テスト】micro\n-soft'
8
8
 
9
9
  >>>
10
10
 
11
11
  >>> re.sub(r'(【テスト】.*)\n・', r'\1・', text)
12
12
 
13
- '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic'
13
+ '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\【テスト】micro\n-soft'
14
14
 
15
15
  ```