验证字符串所需的模式,该字符串可以不包含空格或2个空格 [英] pattern needed for validating string which can contain either no space or 2 spaces

查看:87
本文介绍了验证字符串所需的模式,该字符串可以不包含空格或2个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个可以验证字符串的模式

字符串中没有空格,或者如果存在空格,则应将3个部分用空格分隔.

例如:

有效vith空间
7HKW8 01 MOD,PWA,SYSM,CPEN,CLV743、1110
(第1部分:7HKW8
第2部分:01
第3部分:MOD,PWA,SYSM,CPEN,CLV743、1110)

有效且无空格
7HKW8
MOD,PWA,


无效
7HKW801 MOD,PWA,SYSM,CPEN,CLV743、1110
(只有两部分由空格分隔)
7HKW8 01MOD,PWA,SYSM,CPEN,CLV743、1110
(只有两部分由空格分隔)
7HKW8 01MOD PWA SYSM CPEN CLV743,1110
(它有3个以上的部分,以空格分隔).

I need to generate a pattern which can validate a string

Either no space in a string, or if space exists there should be 3 parts separated by a space.

eg :

Valid vith space
7HKW8 01 MOD,PWA,SYSM,CPEN,CLV743,1110
(Part 1 : 7HKW8
Part 2 : 01
Part 3 : MOD,PWA,SYSM,CPEN,CLV743,1110)

Valid with no space
7HKW8
MOD,PWA,


Invalid
7HKW801 MOD,PWA,SYSM,CPEN,CLV743,1110
(It has only 2 parts seperated by space)
7HKW8 01MOD,PWA,SYSM,CPEN,CLV743,1110
(It has only 2 parts seperated by space)
7HKW8 01MOD PWA SYSM CPEN CLV743,1110
(It has more than 3 parts seperated by space)

推荐答案

为什么使用正则表达式?您没有指定语言,因此C#中包含以下内容:

Why use a regular expression? You didn''t specify a language, so the following is in C#:

var count = (from c in myString
             where c == ' '
             select c).Count();
valid = (count == 2 || count == 0);



根据环境/上下文,我会考虑等到解析字符串的时间,然后将其验证为解析行为的一部分:



Depending on the environment/context, I''d consider wait until it''s time to parse the string, and validate it as part of the act of parsing:

string[] parts = myString.Split(" ");
if (parts.Length != 1 || parts.Length != 3)
{
    return;
}


此处有一个很好的正则表达式教程. ^ ]
关于使用正则表达式进行验证的好文章此处 [此处 [此处 [
There is a good regex tutorial here[^]
A good article on validating with regular expressions here[^]
There is also good regex info here[^]
Finally there is a regular expression tester here[^]


这篇关于验证字符串所需的模式,该字符串可以不包含空格或2个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆