2014-11-06 20 views
0

我需要在文本框中設置不包括空格的字母數量驗證任何人都可以用正則表達式給我建議我需要一個正則表達式來計算沒有空格之間的空白字母嗎?

+2

例子會更好。別忘了展示你的嘗試。 – 2014-11-06 12:17:46

+0

爲什麼有正則表達式? – tom 2014-11-06 12:17:55

+0

此外,請更精確地定義您的問題 - 如果您的文本框中除「字母」和空白之外還有其他內容,將會發生什麼? 「字母」是什麼意思? ASCII字母? Unicode字母? – 2014-11-06 12:20:35

回答

1

這是t中的鏡頭他暗,但假設你希望只允許字母和空格在文本框和字母的總數不能超過10,然後用

^\s*(?:[a-z]\s*){0,10}$ 

測試它live on regex101.com

說明:

^  # Start of string 
\s*  # Optional whitespace 
(?:  # Start of non-capturing group: 
[a-z] # Match a single letter (don't forget the /i option if so desired) 
\s* # Optional whitespace 
){0,10} # between 0 and 10 times 
$  # End of string 
+0

非常感謝你工作完美 – 2014-11-06 12:30:06

0

簡單又甜美的回答:)。 (假設s是字符串)。

System.out.println(s.split("\\s+").length); 

這將打印輸出的所有單詞的數量(包括如果句子中包含的數字)

剛開字母總數的快捷方式,這裏是一個快速和骯髒的方式(不使用註冊例)

int counter=0; 
for(Char c : s.toLowerCase().toCharArray()){ 
    if(c=<'z' && c=>'a') counter++; 
} 
System.out.println(counter); 
+0

這會爲''abc def「'而不是'6'返回'2'。 – 2014-11-06 12:21:08

+0

@TimPietzcker哦對不起,我以爲你想要的總字數 – nafas 2014-11-06 12:22:36

+0

@TimPietzcker我已經更新了我的答案。希望有幫助 – nafas 2014-11-06 12:25:17

0
var str = 'mlsqkf qsq merzo'; 
var n = str.replace(/[^a-z]/gi,'').length; 

demo

+0

大寫字母怎麼辦? – 2014-11-06 12:22:01

+0

確定添加我的標誌;)我編輯 – Sly 2014-11-06 12:36:48

相關問題