tags:

views:

67

answers:

3

Hi, I want to extract last character of a string. In fact I should make clear with example. Following is the string from which i want to extract:

<spara h-align="right" bgcolor="none" type="verse" id="1" pnum="1">
    <line>
        <emphasis type="italic">Approaches to Teaching and Learning</emphasis>
    </line>
</spara>

In the above string i want to insert space between the word "Learning" and "</emphasis>" if there is no space present.

Thanks,

+1  A: 

Have a look at some of the Linq to XML examples on here instead of using Regex.

DaveShaw
no regex is not strictly required Linq 2 xml will also be highly appreciated if any one can help in this regard.
Muhammad Waqas
A: 

Something like the following perhaps?

Regex.Replace(yourString, @"(>[^<]+[^ ])<", @"$1 <");

The solution assumes a sentence is between > and < and is one or more characters long.

Is the sentence really inside XML, or have you extracted it using any of the many XML or DOM methods? For instance, using this:

foreach(node in YourDOM.SelectNodes("//emphasis[@type='italic']"))
{
    string yourString = node.FirstChild.Value;
}

If so, if the string is on its own, you can do this instead, which is way simpler and safer:

Regex.Replace(yourString, "([^ ])$", "$1 "); 

EDIT: I originally missed if there's no space present, the post above is edited with this information

Abel
+1  A: 

With Linq to XML you can do it as follows:

XDocument doc = XDocument.Load("xmlfilename");

foreach (var emphasis in doc.Descendants("emphasis"))
{
      if (emphasis.Value.Last() != ' ')
         emphasis.Value += " ";
}
doc.Save("outputfilename");

Instead of files you may use streams, readers etc in the Load

cellik
+1 I like the clear example and the good advice (but it was not what was asked ;)
Abel