2017-08-29 66 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号

相关问题