开发者

Regex not working in .NET

So I'm trying to match up a regex and I'm fairly new at this. I used a validator and it works when I paste the code but not when it's placed in the codebehind of a .NET2.0 C# page.

The offending code is supposed to be able to split on a single semi-colon but not on a double semi-colon. However, when I used the string

"ent开发者_C百科ry;entry2;entry3;entry4;"

I get a nonsense array that contains empty values, the last letter of the previous entry, and the semi-colons themselves. The online javascript validator splits it correctly. Please help!

My regex:

((;;|[^;])+)


Split on the following regular expression:

(?<!;);(?!;)

It means match semicolons that are neither preceded nor succeeded by another semicolon.

For example, this code

var input = "entry;entry2;entry3;entry4;";
foreach (var s in Regex.Split(input, @"(?<!;);(?!;)"))
    Console.WriteLine("[{0}]", s);

produces the following output:

[entry]
[entry2]
[entry3]
[entry4]
[]

The final empty field is a result of the semicolon on the end of the input.

If the semicolon is a terminator at the end of each field rather than a separator between consecutive fields, then use Regex.Matches instead

foreach (Match m in Regex.Matches(input, @"(.+?)(?<!;);(?!;)"))
    Console.WriteLine("[{0}]", m.Groups[1].Value);

to get

[entry]
[entry2]
[entry3]
[entry4]


Why not use String.Split on the semicolon?

string sInput = "Entry1;entry2;entry3;entry4";
string[] sEntries = sInput.Split(';');
// Do what you have to do with the entries in the array...

Hope this helps, Best regards, Tom.


As tommieb75 wrote, you can use String.Split with StringSplitOptions Enumeration so you can control your output of newly created splitting array

string input = "entry1;;entry2;;;entry3;entry4;;";
char[] charSeparators = new char[] {';'};
// Split a string delimited by characters and return all non-empty elements.
result = input.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);

The result would contain only 4 elements like this:

<entry1><entry2><entry3><entry4>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜