我想在字符串中插入25个字符后插入一个字符串(在本例中为换行符\L
),但在下一个可用空格中只插入 ,以避免分裂如下的话:
This is the example sente\L nce for you.
正确的输出是这样的:
This is the example sentence\L for you.
换行符大约应在每行25个字符后出现,因此较长的示例如下所示:
This is a longer example\L
for you; it actually contains\L
more than 50 characters.
在XQuery中实现这个的最简单方法是什么?
答案 0 :(得分:2)
这是一个XSLT 2.0解决方案 - 只需将其转换为XQuery :
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:value-of select="my:splitAtWords(/*, 25, '\L
')"/>
</xsl:template>
<xsl:function name="my:splitAtWords" as="xs:string?">
<xsl:param name="pText" as="xs:string?"/>
<xsl:param name="pMaxLen" as="xs:integer"/>
<xsl:param name="pRep" as="xs:string"/>
<xsl:sequence select=
"if($pText)
then
(for $line in replace($pText, concat('(^.{1,', $pMaxLen,'})\W.*'), '$1')
return
concat($line, $pRep,
my:splitAtWords(substring-after($pText,$line),$pMaxLen,$pRep))
)
else ()
"/>
</xsl:function>
</xsl:stylesheet>
对以下XML文档应用此转换时:
<t>This is a longer example for you; it actually contains more than 50 characters.</t>
生成了想要的结果:
This is a longer example\L
for you; it actually\L
contains more than 50\L
characters\L
.\L
答案 1 :(得分:1)
我最终使用了提议的解决方案here:
let $text := 'This is a longer example for you; it actually contains more than 50 characters.'
let $text-output := replace(concat($text,' '),'(.{0,25}) ','$1\\L')
return $text-output
返回与上面的@dimitre-novatchev中的XSLT相同的结果:
This is a longer example\L
for you; it actually\L
contains more than 50\L
characters.\L