2011-12-03 9 views
0

を見つけるために私のテキストです:文の50%以上が大文字である場合正規表現は、ここでは、不要な大文字の単語

TESTING TESTING test test test test test 

私は正規表現がtrueを返すようにしたい(またはマッチは)。

この場合、20文字のうち14文字しか大文字ではないため、falseを返します。 AppleScriptでは

、私がやるだろう:Perlで

set a to characters of "abcdefghijklmnopqrstuvwxyz" 
    set ac to characters of "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
    set this_message to characters of "TEST TEST TEST TEST test test test test test test" 
    set x to 0 -- Counter 
    set y to 1 
    repeat with i from 1 to number of items in this_message 
     set this_item to item i of this_message 
     considering case 
      if this_item is not " " then 
       if this_item is in ac then 
        set x to x + 1 
       end if 
      end if 
      if this_item is in {" ", ",", ".", "-"} then 
       set y to y + 1 
      end if 
     end considering 
    end repeat 
    try 
     if (round (x/((count this_message) - y)) * 100) > 50 then 
      return true 
     else 
      return false 
     end if 
    on error 
     return false 
    end try 
+0

私は考えていない。ここで

// Test if more than half of non-whitespace chars in string are CAPs. function isMostlyCaps($text) { $len = preg_match_all('/\S/', $text, $matches); if ($len) { // Check if string has zero length. $capscnt = preg_match_all('/[A-Z]/', $text, $matches); if ($capscnt/$len > 0.5) return TRUE; } return FALSE; } 

は、単語全体の数を考慮したものです正規表現はこの仕事のための正しいツールです。 perlでは 'tr //'を使います。どの言語を使っていますか? – Flimzy

+0

私はPHPを使用するつもりです。しかし、もし仕事のために他の言語が良いとすれば、私はそれを使用します。 – alexy13

答えて

2

が文字列の半分キャップ以上が含まれている場合はTRUEを返し、PHPの関数である:

// Test if more than half of string consists of CAPs. 
function isMostlyCaps($text) { 
    $len = strlen($text); 
    if ($len) { // Check if string has zero length. 
     $capscnt = preg_match_all('/[A-Z]/', $text, $matches); 
     if ($capscnt/$len > 0.5) return TRUE; 
    } 
    return FALSE; 
} 

上記機能は、(空白文字および非文字を含む文字列の全長にキャップの数を比較します)。あなたは非空白文字の数を比較したい場合は、関数が簡単に変更されます。

// Test if more than half of "words" in string are all CAPs. 
function isMostlyCapWords($text) { 
    // For our purpose a "word" is a sequence of non-whitespace chars. 
    $wordcnt = preg_match_all('/\S+/', $text, $matches); 
    if ($wordcnt) { // Check if string has no words. 
     $capscnt = preg_match_all('/\b[A-Z]+\b/', $text, $matches); 
     if ($capscnt/$wordcnt > 0.5) return TRUE; 
    } 
    return FALSE; 
} 
+0

thoural答えをありがとう – alexy13

1

を:

sub mostly_caps { 
    my $string = shift; 
    my $upper = $string =~ tr/A-Z//; 
    my $lower = $string =~ tr/a-z//; 
    return $upper >= $lower; 
} 

そして、ボーナスポイントのために、引数として任意の割合を取りバージョン:

sub caps_pct { 
    my ($string, $pct) = @_; 
    my $upper = $string =~ tr/A-Z//; 
    my $lower = $string =~ tr/a-z//; 
    return ($upper/($upper+$lower) >= $pct/100; 
} 

これをPHPや他の言語に適合させるのは簡単です。ここ

+0

+1、これは50%でしか動作しません:) – FailedDev

+0

@FailedDev:これは必須条件でしたか?私は、別の式を使って任意のパーセンテージに簡単に対処できると考えています。 – Flimzy

+0

もっと一般的な解決方法が良いかもしれませんが、よくあります。 – FailedDev

関連する問題