Srinivas R Srinivas R -4 years ago 104
ASP.NET (C#) Question

Extract Number from String using C#

I have Rss feed using XDocument.Load("Somelink"); I am getting XML output from the server.

<item>
<title>Senior Web Developer</title>
<link>Some link</link>
<guid isPermaLink="false">Some link</guid>
<description><![CDATA[University of UK &lt;br /&gt;Salary: £39,324 to £46,924 pa]]></description>
</item>


In description tag i am getting company information and salary, I need only Salary part in that description, How to extract salary from that link.

var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
description = x.Element("description").Value
});


How to extract that salary from description tag . I want to display that salary in two different labels.

I need output in Grid view Salary from and Salary to. I tried Regex.Match method its giving only first two digits.

Code :-

<asp:GridView ID="gRss" runat="server" AutoGenerateColumns="false"
ShowHeader="false" CssClass="table table-bordered table-striped">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table class="table table-bordered table-striped">
<tr>
<td class="info"><%#Eval("Title") %></td>
</tr>
<tr>
<td><%#Eval("SalaryFrom") %></td>
</tr> <tr>
<td><%#Eval("SalaryTo") %></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


C# code

List<Feeds> feeds = new List<Feeds>();
try
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load("Some link");
var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
description = x.Element("description").Value
});


if(items != null)
{
foreach(var i in items)
{

// string resultString = Regex.Match(i.description, @"\d+").Value;
//resultString = Regex.Match(subjectString, @"\d+").Value;
var match = Regex.Match(i.description, @": £(?<from>.*?) to £(?<to>.*?) ");
var from = match["from"].Value;
var to = match["to"].Value;
Feeds f = new Feeds
{
Title = i.title,
Description = resultString
};
feeds.Add(f);
}
}
gRss.DataSource = feeds;
gRss.DataBind();

}

Answer Source

You can use Regex.Matches to extract the salary range.

var matches1 = Regex.Matches(descriptionValue, "£([0-9,]+)");   
for(int i=0; i < matches1.Count; i++)
     Console.WriteLine("Parameters >> " + i + "\t" + matches1[i].Value);

Here you will have from on first and to on second location of result returned by Regex.Matches.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download