Sort numbers with letters in alphabetical order

I have a database on my website with a long list of No. (product number) containing letters (Exp. TC-345, TC-234 or HC-236W 123-234-PWD ...)

Can I sort # on a website numerically and alphabetically?

We currently store it in alphabetical order, so the order is (10-PDW, 100-PDW, 110-PDW 2-PDW) We would like to change it to (2-PDW, 10-PDW, 100-PDW, 110-PDW )

My developers say: "The number of columns can never be sorted numerically. We will need to add another numerical field to the database for all color paths, and then sort this field numerically. Now these numbers are listed in alphabetical order."

How do you sort numbers with letters? We would like not to add a number field - this is just an extra job. Is there any new way to do this?

+4
source share
2 answers

It is possible. One way is to use a function to weight strings, which gives much more weight to numbers than letters. Something like that:

letbers = ["10-PDW", "100-PDW", "110-PDW", "2-PDW"] def weight(letber): if letber == "": return 0 n = ord(letber[-1]) if letber[-1] in "0123456789": n *= 256^6 # 6 because maximum key length is 6 return 256*n + weight(letber[:-1]) print sorted(letbers, key = weight) 
0
source

If you add the following conversion function (in scala), you can alphabetically and numerically sort all the lines:

 def transformed(s: String): String = { s.replaceAll("""(?<=[^\d]|^)(\d)(?=[^\d]|$)""","""000$1""") .replaceAll("""(?<=[^\d]|^)(\d\d)(?=[^\d]|$)""","""00$1""") .replaceAll("""(?<=[^\d]|^)(\d\d\d)(?=[^\d]|$)""","""0$1""") } 

Basically, it replaces each numeric number with a fixed integer width, so the alphabetical sort in this case is equal to the numeric sort.

Testing at your input:

 > val s = List("10-PDW", "100-PDW", "110-PDW", "2-PDW") > s.sortBy(transformed) res2: List[String] = List(2-PDW, 10-PDW, 100-PDW, 110-PDW) 

This only works if you are sure that all numbers are below 9999. If you have more numbers, you should consider expanding the function or doing something else.

0
source

Source: https://habr.com/ru/post/1494753/


All Articles