2016-10-09 4 views
1

2つ以上の連続する大文字とそれ以上の文法規則を含む文を無視するという単純な問題があります。2つの連続する大文字の文を無視するためのPython正規表現

問題:定義によって、正規表現は文字列'This is something with two CAPS.'と一致してはいけませんが、一致します。

コード:

''' Check if a given sentence conforms to given grammar rules 

    $ Rules 
     * Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.) 
     * Then lowercase character follows. 
     * There must be spaces between words. 
     * Then the sentence must end with a full stop(.) after a word. 
     * Two continuous spaces are not allowed. 
     * Two continuous upper case characters are not allowed. 
     * However the sentence can end after an upper case character. 
''' 

import re 


# Returns true if sentence follows these rules else returns false 
def check_sentence(sentence): 
    checker = re.compile(r"^((^(?![A-Z][A-Z]+))([A-Z][a-z]+)(\s\w+)+\.$)") 
    return checker.match(sentence) 

print(check_sentence('This is something with two CAPS.')) 

出力:

<_sre.SRE_Match object; span=(0, 32), match='This is something with two CAPS.'> 

答えて

0

それはそれはであるよりも、マイナス(悪い文章であるすべての文を見つける。)で、あなたの正規表現を書くために、おそらく簡単ですポジティブ。

checker = re.compile(r'([A-Z][A-Z]|[ ][ ]|^[a-z])') 
check2 = re.compile(r'^[A-Z][a-z].* .*\.$') 
return not checker.findall(sentence) and check2.findall(sentence) 
+0

位置を主張する、私はテストスイートを持っており、ここにthaの結果がありますt –

+0

??? @ aswin-mohanの結果はどこにありますか? – 2ps

+0

もっと重要なのは、なぜ機能するのは難しいのでしょうか? – 2ps

0

ネガティブ先読みは、テストする文字列の先頭にのみ適用されます。

第二キャプチャグループ(^(?![A-Z][A-Z]+))

^はこれが困難である文字列

否定先読みの開始(?![A-Z][A-Z]+)

"This will NOT fail."

"THIS will fail."

+0

ありがとう。変更された正規表現を書いてください。 –

関連する問題