user222427
user222427

Reputation:

C# string replacement question

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 ~

Upvotes: 5

Views: 447

Answers (5)

Ed James
Ed James

Reputation: 10607

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!)

Upvotes: 6

pm100
pm100

Reputation: 50110

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

so either split on "~", or use regex

Upvotes: 1

Andy Rose
Andy Rose

Reputation: 16974

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

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

Upvotes: 4

Rubens Farias
Rubens Farias

Reputation: 57936

What about:

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

Upvotes: 4

Mark Dickinson
Mark Dickinson

Reputation: 6633

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.

Upvotes: 12

Related Questions