Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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)
Posted
Updated 19-Apr-11 5:49am
v2
Comments
vinu_p 19-Apr-11 8:34am    
I am validating contents in a xml , regex will be easy instead of extracting and doing some c# code

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

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:

C#
string[] parts = myString.Split(" ");
if (parts.Length != 1 || parts.Length != 3)
{
    return;
}
 
Share this answer
 
v2
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[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900