2

文字列内の単一のアルファベット文字の出現ごとにすべてのインデックスを検索したいと考えています。単一の char html コードをキャッチしたくありません。

これが私のコードです:

import re
s = "fish oil B stack peanut c <b>"
words = re.finditer('\S+', s)
has_alpha = re.compile(??????).search
for word in words:
    if has_alpha(word.group()):
        print (word.start())

望ましい出力:

9
24
4

3 に答える 3

6

これはそれを行います:

r'(?i)\b[a-z]\b'

それを分解する:

  • 大文字と小文字を区別しない一致
  • 単語境界
  • 手紙
  • 単語境界

コードは次のように簡略化できます。

for match in re.finditer(r'(?i)\b[a-z]\b', s):
   print match.start()
于 2013-04-23T12:54:38.077 に答える
2

(必要に応じて)フォーマットを使用しますが、単純なチェックのみを追加します。

import re
s = "fish oil B stack peanut c <b>"
words = re.finditer('\S+', s)
has_alpha = re.compile(r'[a-zA-Z]').search
for word in words:
    if len(word.group()) == 1 and has_alpha(word.group()):
        print (word.start())
>>> 
9
24
于 2013-04-23T13:25:11.277 に答える