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 ~

5 Answers 5

12

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.

Sign up to request clarification or add additional context in comments.

Comments

6

string listItem = Regex.Replace(listBox1.SelectedItem.ToString(), "~[0-9]{1,6}", string.Empty);

should do the trick (can't remember if you have to escape ~ though!)

4 Comments

i would love to do the regex, but i cant get it to compile. it thinks there is a newline starting at the "
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.
@Mike, just a missing "; try it again
@Rubens thanks for the edit, hadn't noticed it'd munched my syntax!
4

What about:

string listItem = 
      listBox1.SelectedItem.ToString().Substring(0, 
           listBox1.SelectedItem.ToString().IndexOf("~"));

2 Comments

Man, I mainly voted to get you from 9,990 to 10k. But you seem to have hit the cap for today already. :-)
@Tomalak, I already made 232 pts today; it's hard to get an accepted answer when you need one =)
4

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

string listItem = listBox1.SelectedItem.toString();
listItem = listitem.SubString(0, listItem.IndexOf("~"));

Comments

1

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

so either split on "~", or use regex

Comments