Regex

L

lavu

I am trying to form a regex to search my string and give me substrings
follwing the pattern that it
split the string at every occurence of hyphen - character but not if a
\ precedes it.

ie. if a string is like this:
-xyz -rer\-er -fgg12\-33

I want to get foll. substrings using the regex.split method
-xyz
-rer\-er
-fgg12\-33

I am new to regex and have been trying some combinations with no
success. Any help will be appreciated.
 
J

Jani Järvinen [MVP]

Hi Lavu,
I am trying to form a regex to search my string and give me substrings
follwing the pattern that it
split the string at every occurence of hyphen - character but not if a
\ precedes it.

I hope this isn't school homework you are trying to do. :) But here goes
anyway. Try this C# code:

-------------------------------
string input = "-xyz -rer\\-er -fgg12\\-33";
Regex regex = new Regex("(?<!\\\\)-");
string[] elements = regex.Split(input);
foreach (string element in elements)
{
if (element != "")
{
MessageBox.Show("Element: -" + element);
}
}
-------------------------------

This would output (after the first empty element):

-xyz
-rer\-er
-fgg12\-33

So the regular expression (without C# double backslashes, you could use the
@ sign in front of the strings to avoid them):

(?<!\\)-

This utilizes the so-called "zero-width negative lookbehind assertion"
grouping construct in regular expressions. Hope this makes sense.

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 
L

lavu

wow ! that would have taken me a while to figure out . thanku Mr.Jani
.......
and no this is not a school project.done with school a long time ago :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top