2017-08-29 336 views
1

我正在嘗試創建一個正則表達式來匹配所有字母或空格或具體數字。正則表達式來匹配任何字母,空格或具體數字

這是我的。

([a-zA-Z\s24]*) 
 #but this is matching a 2 or a 4, i need exactly 24 only 

ex: 
- asdfafasf asfasdf #should match asdfafasf asfasdf 
- asdf asdf asdf 24 #should match asdf asdf asdf 24 
- asdf24asdfasdf as #should match asdf24asdfasdf as 
- asdfadf2 asdf  #should match asdfadf 
- asdfasdf kljl 6 #should match asdfasdf kljl 

https://regex101.com/r/iNWuRb/1

+2

它應該是:'([A-ZA-Z \ S] + | 24) ' – anubhava

+2

嘗試使用'^(?: 24 | [a-zA-Z \ s])+' –

+0

嘗試使用此網站。它可以幫助[正則表達式測試](https://regex101.com) – DaFois

回答

1

你把序列變成一個角色類。字符類是爲了匹配在字符類中定義的單個字符,因此,你所做的不能工作。

您需要使用一個分組結構,一個替代組和acc。到預期的比賽中,你只需要匹配字符串的開始:

^(?:24|[a-zA-Z\s])+ 

regex demo

詳細

  • ^ - 串
  • (?:24|[a-zA-Z\s])+的開始 - 一次或多次出現:
    • 24 - 一個子24
    • | - 或
    • [a-zA-Z\s] - ASCII字母或空格
+0

是的,我認爲這是接近除了現在我需要分組的第二個結果。第1組應該是所有字母(或24),直到它遇到一個數字。第2組應該是數字。 – btorkelson

+0

https://regex101.com/r/iNWuRb/1 – btorkelson

+1

@btorkelson:['^((?: 24 | [a-zA-Z \ s] *)+)(\ d *)'](https: //regex101.com/r/iNWuRb/3)? –

0

我想你想:

([a-zA-Z\s]*|24) 

然後你得到你的AZ \ S的組或24號

相關問題