views:

147

answers:

5

Quick question. I have a listbox being populated from a directory listing. Each file contains its name and ~#####. I'm trying to read it all into a string and replace the ~#### with nothing. The #### could be digits from length 1-6 and could be anything from 0-9. Here's the code I'm using:

string listItem = (listBox1.SelectedItem.ToString().Replace("~*",""));

Example:

Here223~123  --->  Here
Here224~2321 ----> Here

I can't replace any number because I need the numbers before the ~

+12  A: 

Try

listItem.Split("~")[0]

This should give you the first string in an array of strings, that way you've lost the tilda and trailing string after that.

Mark Dickinson
+6  A: 
Ed Woodcock
i would love to do the regex, but i cant get it to compile. it thinks there is a newline starting at the "
Mike
that's odd, Regex is normally pretty good with newlines ('\n's). Regex is also a great tool in your arsenal for problems like this, especially as they get more complex, as Split is not quite as specific.
Ed Woodcock
@Mike, just a missing `"`; try it again
Rubens Farias
@Rubens thanks for the edit, hadn't noticed it'd munched my syntax!
Ed Woodcock
+4  A: 

What about:

string listItem = 
      listBox1.SelectedItem.ToString().Substring(0, 
           listBox1.SelectedItem.ToString().IndexOf("~"));
Rubens Farias
Man, I mainly voted to get you from 9,990 to 10k. But you seem to have hit the cap for today already. :-)
Tomalak
@Tomalak, I already made 232 pts today; it's hard to get an accepted answer when you need one =)
Rubens Farias
+4  A: 

You may be better of using the Substring(int startIndex, int lenght) method:

string listItem = listBox1.SelectedItem.toString();
listItem = listitem.SubString(0, listItem.IndexOf("~"));
Andy Rose
+1  A: 

the point is that string.replace does not do regular expressions

so either split on "~", or use regex

pm100