Help us understand the problem. What is going on with this article?

python 正規表現で奇数番目、偶数番目の文字のパターンを見る

正規表現を使った偶数、奇数番目の文字判定

pythonで文字列の奇数番目、偶数番目文字を判定した方法を共有します。

例えば

RDULULDURURLRDULRLR

このような文字列で奇数番目の文字にLが入っていないことを、また偶数番目の文字にRが入っていないことを確認したいです。

そこで今回は正規表現を使いました。

import re

string = input()
pattern = re.compile(r'^([^L][^R])*[^L]?$')
if pattern.match(string):
    print('Yes')
else:
    print('No')

re.compileとしておくと繰り返しそのパターンを探していく場合に高速になります。

上記の正規表現の意味は以下の通りです。

r:文字列の先頭に書いておくとバックスラッシュ等がエスケープされます

^:行の先頭を表す

:0回以上の繰り返し   例:ab 合致パターン: a,ab,abb,abbb,...

$:行の末尾

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away