4

私のウェブサイトには、すべて文字を含む # (製品番号) の長いリスト (Exp. TC-345、TC-234、または HC-236W 123-234-PWD...) を含むデータベースがあります。

Web サイトの # を数値およびアルファベット順に並べ替えることはできますか?

現在、アルファベット順に格納されているため、順序は (10-PDW、100-PDW、110-PDW 2-PDW) です (2-PDW、10-PDW、100-PDW、110-PDW) に変更したいと考えています。

私の開発者は、「カラーウェイ番号を数字でソートすることはできません。すべてのカラーウェイのデータベースに別の数値フィールドを追加してから、そのフィールドを数値でソートする必要があります。現在、これらの数字はアルファベット順に並べられています。」

数字を文字で並べ替えるにはどうすればよいですか? 数値フィールドを追加することは避けたいと思います - それは余分な作業です。これを行うための新しいテクニックはありますか?

4

2 に答える 2

0

If you add the following transformation function (in scala), then you can alphabetically and numerically sort all strings:

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 every number occurence by a fixed width integer, so that the alphabetical sorting equals the numerical sorting in that case.

Test on 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 works only if you are sure that all numbers are below 9999. If you have more digits, then you should consider to expand the function or do something else.

于 2014-01-23T11:26:58.643 に答える