Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to get "sortable" chapters from contract chapter numbers

i am looking for a regular expression to sort chapters of a contract. Therefore i want to transform this chapter numbering to a 2-digit format "dd.dd.dd". Chapters are e.g.:

1.
1.2.1
...
2.10.4

Chapter numbering:

  • 1 – 3 digit sections possible
  • each section can have 1 or 2 digits
  • dots are optional

My way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • regex first digits: "\d+\."
  • regex second digits: "\.\d+\.?"
  • third digits are extracted with a split() function.
  • i then assemble the 3 sections to a 2-digit-format (e.g. 02.10.04).

Problem:

  • my solution seems not very safe. Because sometimes a dot is used after a digit section, sometimes it is not.
  • maybe there is an easier way to simply "format"

Thanks for your support!

Regards,
Fabian

>Solution :

You may try the following find and replace, in regex mode:

Find:    (?<=\.|^)(\d)(?=\.|$)
Replace: 0$1

This regex pattern will capture all single digit path values which are sandwiched on both sides by either dots, or the start/end of the string. The replacement prepends a leading zero to make the digits have a width of two. Here is a demo showing that the logic is working.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading