Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip leading spaces only

Tags:

xslt

xslt-2.0

Given element:

 <comments>  comments
go here
</comments>

How can I strip what may be multiple leading space characters. I cannot use normalize space because I need to retain newlines and such. XSLT 2.0 ok.

like image 994
johkar Avatar asked Jul 06 '10 21:07

johkar


People also ask

How do I strip leading spaces in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


2 Answers

In XPath 1.0 (means XSLT 1.0, too):

substring($input, 
          string-length(
                        substring-before($input, 
                                         substring(translate($input, ' ', ''), 
                                                   1,
                                                   1)
                                         )
                       ) +1
          )

Wrapped in an XSLT transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:variable name="input"
   select="string(/*/text())"/>

 <xsl:template match="/">
   '<xsl:value-of select=
   "substring($input,
              string-length(
                            substring-before($input,
                            substring(translate($input, ' ', ''),
                                      1,
                                      1)
                                             )
                            ) +1
              )
   "/>'
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<t>    XXX   YYY Z</t>

the correct, wanted result is produced:

   'XXX   YYY Z'
like image 51
Dimitre Novatchev Avatar answered Sep 20 '22 07:09

Dimitre Novatchev


Use the replace() function:

replace($input,'^ +','')

That handles leading space characters only up to the first non-space. If you want to remove all leading whitespace characters (i.e. space, nl, cr, tab) up to the first non-whitespace, use:

replace($input,'^\s+','')
like image 40
Jim Garrison Avatar answered Sep 22 '22 07:09

Jim Garrison