質問するログイン新規登録

回答編集履歴

3

汎用的な正規表現を追加

2021/02/15 07:23

投稿

ppaul
ppaul

スコア24672

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

2

例の間違いを修正

2021/02/15 07:23

投稿

ppaul
ppaul

スコア24672

answer CHANGED
@@ -1,8 +1,8 @@
1
1
  こういうのでどうでしょう。
2
2
 
3
3
  ```python
4
- >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\ 【テスト】micro\n-soft'
4
+ >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\n【テスト】micro\n-soft'
5
5
  >>>
6
6
  >>> re.sub(r'(【テスト】.*)\n・', r'\1・', text)
7
- '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\【テスト】micro\n-soft'
7
+ '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\n【テスト】micro\n-soft'
8
8
  ```

1

例を追加

2021/02/15 02:12

投稿

ppaul
ppaul

スコア24672

answer CHANGED
@@ -1,8 +1,8 @@
1
1
  こういうのでどうでしょう。
2
2
 
3
3
  ```python
4
- >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic'
4
+ >>> text = '【テスト】win\n・dow\n【テスト】ap\n・ple\n【テスト】pana\n・sonic\ 【テスト】micro\n-soft'
5
5
  >>>
6
6
  >>> re.sub(r'(【テスト】.*)\n・', r'\1・', text)
7
- '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic'
7
+ '【テスト】win・dow\n【テスト】ap・ple\n【テスト】pana・sonic\【テスト】micro\n-soft'
8
8
  ```