前提・実現したいこと
Pythonの正規表現で名前付きグループに同じ名前を使いたい。
選択(|
)で分岐させ、同じ名前を使えるようにしたい。
(VB.NETではできるようです。)
python
1>>> re.compile(r'(?:"(?P<hoge>\w+)"|(?P<hoge>\w+))')
のようにhoge
というグループ名を複数箇所で使いたい
発生している問題・エラーメッセージ
python
1>>> import re 2>>> re.compile(r'(?:"(?P<hoge>\w+)"|(?P<hoge>\w+))') 3Traceback (most recent call last): 4 File "<stdin>", line 1, in <module> 5 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 234, 6in compile 7 return _compile(pattern, flags) 8 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 286, 9in _compile 10 p = sre_compile.compile(pattern, flags) 11 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_compile.py", l 12ine 764, in compile 13 p = sre_parse.parse(p, flags) 14 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", lin 15e 930, in parse 16 p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0) 17 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", lin 18e 426, in _parse_sub 19 not nested and not items)) 20 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", lin 21e 816, in _parse 22 p = _parse_sub(source, state, sub_verbose, nested + 1) 23 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", lin 24e 426, in _parse_sub 25 not nested and not items)) 26 File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", lin 27e 813, in _parse 28 raise source.error(err.msg, len(name) + 1) from None 29re.error: redefinition of group name 'hoge' as group 2; was group 1 at position 23 30 31redefinition of group name 'hoge' as group 2; was group 1 at position 23
該当のソースコード
python
1>>> re.compile(r'(?:"(?P<hoge>\w+)"|(?P<hoge>\w+))')
試したこと
hoge1
とhoge2
にしてみた
python
1>>> re.compile(r'(?:"(?P<hoge1>\w+)"|(?P<hoge2>\w+))') 2re.compile('(?:"(?P<hoge1>\w+)"|(?P<hoge2>\w+))')
これでできるが、実現したいこととは異なっている
補足情報(FW/ツールのバージョンなど)
python
1>>> sys.version 2'3.7.1 (default, Nov 6 2018, 18:46:03) \n[Clang 10.0.0 (clang-1000.11.45.5)]'

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/14 02:24