开发者

Should i use regular expression in this situation?

I have a xml file containing certain expressions like this :-

1. AAaaaaa-1111 
2. AAaaa-1111-aaa 
3. AA11111-11111 
4. AA111-111-111111

(AA static text) (aaaa-Any alphabet only) then hyphen (1111 - any digit only)

I was thinking i should write regular expression for these I believe regex should be the right approach.

But this XML file is dynamic. User can remove or add different expressions in the list. So How can i use regula开发者_开发百科r expression here? Is there any dynamic regular expression kind of thing. Show me the light here please.

UPDATE:- I am using these expressions to validate user input. So whatever user is entering in a box, it should be matched with any of these expressions from the list.

For Example:-

If user enters

AAabc-4567-trr

, then it should be validated coz it matches with 2nd expression in the list


Well,

What I assume from your question is that:

A is the letter A
a is any letter
1 is any number

That's the only way I see AAabc-4567-trr matches AAaaa-1111-aaa

Is that correct?

If it is correct, yes, you could use Regular Expressions. What you need to do is translate your patterns to regex patterns. Assuming you have a new pattern:

AAA-aaa-111

to obtain the regex that will recognize that pattern, all you have to do is translate that pattern into regex patterns. For example:

string xmlPattern = "AAA-aaa-111"
string regexPattern = xmlPattern.Replace("a", "[a-zA-Z]").Replace("1", @"\d");

Edit:
You should take in count other characters that have special meanings in Regular Expressions, and translate/encode them properly. Maybe classify them. For example, these characters:

., $, ^

can be easily translated to regex patterns just encoding them with a \ before, so they will become:

\., \$, \^, ...

If you can specify what is the format of the validation patterns you are storing in the XML files, I could help you a little more, but I'm just writing this answer kind of blind ;)


Regular expressions that match certain sets of characters in a certain order are fairly simple. For example, this will match #2 (AAaaa-1111-aaa):

[A-Z]{2}[a-z]{3}-[0-9]{4}-[a-z]{3}

Breaking it down:

  • [A-Z]: Any character from A to Z. So any alphabetic, uppercase character.
  • {2}: Two of the previous item.

The rest of it works in the same way. The hyphens between things are there to match the hyphens in your expected input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜