user282807
user282807

Reputation: 925

extract string with linq

Is there a nice way to extract part of a string with linq, example: I have

string  s = "System.Collections.*";

or

string s2 = "System.Collections.Somethingelse.*";

my goal is to extract anything in the string without the last '.*'

thankx I am using C#

Upvotes: 2

Views: 1353

Answers (3)

lunadir
lunadir

Reputation: 339

With the regex:

string input="System.Collections.Somethingelse.*";
string output=Regex.Matches(input,@"\b.*\b").Value;

output is:

"System.Collections.Somethingelse"

(because "*" is not a word) although a simple

output=input.Replace(".*","");

would have worked :P

Upvotes: 0

ChrisF
ChrisF

Reputation: 137128

The simplest way might be to use String.LastIndexOf followed by String.Substring

int index = s.LastIndexOf('.');

string output = s.Substring(0, index);

Unless you have a specific requirement to use LINQ for learning purposes of course.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190905

You might want a regex instead. (.*)\.\*

Upvotes: 0

Related Questions