Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am using Regex.Split to split my string as:

C#
string str = "12$34$45";
string [] result= Regex.Split(str,"$");


but it is not splitting ..When i tried splitting by # then it works.

What I have tried:

C#
string str = "12$34$45";
string [] result= Regex.Split(str,"$");
Posted
Updated 5-May-18 2:32am

Because '$' is a special meaning in a RegEx, knowing this is regEx 101.
you need to escape it as @"\$"

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
Comments
xpertzgurtej 5-May-18 8:06am    
with single $ it works. but for :
string str = "12$$34$$45";
string [] result= Regex.Split(str, @"\$$");

it doesn't work. How to handle this?

Actually i want to split my string and separator may be of multiple characters.
e.g.:
string str = "12$$34$$45";
string separator = "$~$";
string [] result= Regex.Split(str, @"\"+ separator + "");
Kenneth Haugland 5-May-18 8:47am    
You need the \ before all the times you are going to match the special case $
string[] result = Regex.Split(str, @"\$\$");
Patrice T 5-May-18 8:52am    
Try @"\$+"
xpertzgurtej 5-May-18 8:31am    
I found the solution:
string str = "12$$34$$45";
string separator = "$$";

string[] partsFromString = str.Split(new string[] { separator }, StringSplitOptions.None);
Richard MacCutchan 5-May-18 8:36am    
A slightly better way would be
string[] partsFromString = str.Split(new Char[] {'$'}, StringSplitOptions.RemoveEmptyEntries);

As that allows any number of dollar signs.
Just do this:
string[] result = Regex.Split(str, "[$]");

The operator [ ] represents a class of characters, so the regex trys to match all that is inside these brackets.

For multiple $ (2 in this case):
string[] result = Regex.Split(str, "[$]{2}");
 
Share this answer
 
v2

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