Pythonを使用して、セクションとサブセクションのファイルを1行ずつ検索しています。
*** Section with no sub section
*** Section with sub section ***
*** Sub Section ***
*** Another section
セクションは 0 ~ 2 個のスペースで始まり、その後に 3 つのアスタリスクが続きます。サブセクションには 2 つ以上の空白とアスタリスクが続きます。
「***」なしでセクション/サブセクションを書き出します。現在(re.subを使用)。
Section: Section with no sub section
Section: Section with sub section
Sub-Section: Sub Section
Section: Another Section
質問 1 : セクション/サブセクション名にキャプチャ グループとしてアクセスできる、キャプチャ グループを含む python 正規表現はありますか?
質問 2 : 正規表現グループを使用すると、セクションまたはサブセクションをどのように識別できますか? (おそらく、match.group 内の /content の数に基づいて)?
例 (非稼働):
match=re.compile('(group0 *** )(group1 section title)(group2 ***)')
sectionTitle = match.group(1)
if match.lastindex = 0: sectionType = section with no subs
if match.lastindex = 1: sectionType = section with subs
if match.lastindex = 2: sectionTpe = sub section
以前の試み 別々の正規表現と if ステートメントを使用してセクションまたはサブセクションをキャプチャできましたが、すべてを一度に実行したいと考えています。以下の行のようなもの。2番目のグループの貪欲さに問題があります。
'(^\*{3}\s)(.*)(\s\*{3}$)'
貪欲またはオプションのグループを連携させることができないようです。 http://pythex.org/は、この時点で非常に役に立ちました。
また、アスタリスク '(*{3})' をキャプチャして、見つかったグループの数に基づいてセクションまたはサブセクションかどうかを判断しようとしました。
sectionRegex=re.compile('(\*{3})'
m=re.search(sectionRegex)
if m.lastindex == 0:
sectionName = re.sub(sectionRegex,'',line)
#Set a section flag
if m.lastindex ==1:
sectionName = re.sub(sectionRegex,''line)
#Set a sub section flag.
ありがとう 多分私はこれで完全に間違っています。どんな助けでも大歓迎です。
最新の更新 Pythex、回答、およびその他の調査で遊んでいます。私は今、単語をキャプチャすることに多くの時間を費やしています:
^[a-zA-Z]+$
アスタリスクの一致数を数えて「レベル」を決定します。私はまだ2つから3つの「グループ」に一致する単一の正規表現を探しています。存在しない場合があります。
ありがとう。