2

As a premise, I have an HTML text, with some <ol> elements. These have a start attribute, but the framework I'm using is not capable to interpret them during a PDF conversion. So, the trick I am trying to apply is to add a number of invisible <li> elements at the beginning.

As an example, suppose this input text:

<ol start="3">
   <li>Element 1</li>
   <li>Element 2</li>
   <li>Element 3</li>
</ol>

I want to produce this result:

<ol>
   <li style="visibility:hidden"></li>
   <li style="visibility:hidden"></li>
   <li>Element 1</li>
   <li>Element 2</li>
   <li>Element 3</li>
</ol>

So, adding n-1 invisible elements into the ordered list. But I'm not able to do that from Java in a generalized way.

Supposing the exact case in the example, I could do this (using replace, so - to be honest - without regex):

htmlString = htmlString.replace("<ol start=\"3\">",
            "<ol><li style=\"visibility:hidden\"></li><li style=\"visibility:hidden\"></li>");

But, obviously, it just applies to the case with "start=3". I know that I can use groups to extract the "3", but how can I use it as a "variable" to specify the string <li style=\"visibility:hidden\"></li> n-1 number of times? Thanks for any insight.

Andrea
  • 6,032
  • 2
  • 28
  • 55
  • you could simple repeat it. example: `(
  • [\s\S]*?
  • )([\s\S]*?)` this selects the fist two li - containers – SL5net Sep 06 '18 at 14:04
  • Using Python, you could use `re.sub` with a callback method: `re.sub(r'
      ', lambda m: '
        ' + ('\n
      1. ' * int(m.group(1))), s)`
    – tobias_k Sep 06 '18 at 14:09
  • @SL5net: thank you, but unfortunately this does not solve my problem. In fact, I don't know in advance the number of occurrences. – Andrea Sep 06 '18 at 14:10
  • @tobias_k: That's the power of Phyton :) in my case, I am developing a webapp with Java, so it's useless to me. But I hope your comment could help others. – Andrea Sep 06 '18 at 14:11
  • 1
    @Andreaジーティーオー Looks like Java has a replace-with-callback function now, too. :-) – tobias_k Sep 06 '18 at 14:24