1

I have a string of 5 characters out of which the first two characters should be in some list and next three should be in some other list.

How could i validate them with regular expressions?

Example:

  • List for First two characters {VBNET, CSNET, HTML)}

  • List for next three characters {BEGINNER, EXPERT, MEDIUM}

My Strings are going to be: VBBEG, CSBEG, etc.

My regular expression should find that the input string first two characters could be either VB, CS, HT and the rest should also be like that.

5 Answers 5

1

Would the following expression work for you in a more general case (so that you don't have hardcoded values): (^..)(.*$) - returns the first two letters in the first group, and the remaining letters in the second group.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. My First two characters extracted should match the first two characters of the word in the list specified. Any threads on this? Thanks in advance...
@Rupesh The list matching would depend on what programming language you are using.
1

something like this:

^(VB|CS|HT)(BEG|EXP|MED)$

Comments

1

This recipe works for me:

^(VB|CS|HT)(BEG|EXP|MED)$

Comments

0

I guess (VB|CS|HT)(BEG|EXP|MED) should do it.

Comments

0

If your strings are as well-defined as this, you don't even need regex - simple string slicing would work.

For example, in Python we might say:

mystring = "HTEXP"

prefix = mystring[0:2]
suffix = mystring[2:5]

if (prefix in ['HT','CS','VB']) AND (suffix in ['BEG','MED','EXP']):
    pass # valid!
else:
    pass # not valid. :(

Don't use regex where elementary string operations will do.

1 Comment

@Rupesh: A regexp can certainly be used to solve this problem - in this case the complexity of the code is about the same. My general advice, however, is to think carefully before using regular expressions for everything. Often "plain" string methods will do just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.