Sergey
Sergey

Reputation: 441

How i can optimize Xpath expression?

I need to concat first 5 symbols of string with 4 last and divide them with '_'. I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)

concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))

Upvotes: 0

Views: 189

Answers (3)

Michael Kay
Michael Kay

Reputation: 163282

Here's an XPath 2.0 solution:

replace(//element1/element2, '^(.{5}).*(.{4})$', '$1_$2')

Unlike your solution, it assumes the string is at least 9 characters long.

Upvotes: 1

Iurii  Kvashuk
Iurii Kvashuk

Reputation: 409

As for me,it's pretty OK. But your code takes 5 last symbols. In order to fix that, I use string-length(//element1/element2)-3 Maybe, text() is not necessary, but I've processed the code via xslt.

Whole expression looks like that:

concat(substring(//element1/element2,1,5),"_",substring(//element1/element2,string-length(//element1/element2)-3))

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With XPath v2.0 you may apply the following (to concat first 5 symbols of string with 4 last and divide them with '_') :

//element1/element2/text()/concat(substring(.,1,5),"_",substring(.,string-length(.)-3))
  • . - points to the current selected node

Note, to extract the last 4 characters you should specify starting position as string-length(.)-3

Upvotes: 1

Related Questions