使用数字和字母对字母进行数字排序 [英] Sort numbers with letters numerically and alphabetically

查看:149
本文介绍了使用数字和字母对字母进行数字排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个数据库,其中包含所有字母的#号(产品编号)的长列表(Exp.TC-345,TC-234或HC-236W 123-234-PWD ...)

I have a Database on my website with a Long List of #'s (Product #'s) all containing letters (Exp. TC-345, TC-234 or HC-236W 123-234-PWD...)

我们可以按数字和字母顺序对网站上的#进行排序吗?

Can we numerically and alphabetically sort the #'s on the website?

当前,我们按字母顺序存储它,因此顺序为(10-PDW,100-PDW,110-PDW 2-PDW) 我们想将其更改为(2-PDW,10-PDW,100-PDW,110-PDW)

Currently we store it alphabetically, so the order is (10-PDW, 100-PDW, 110-PDW 2-PDW) We would like to change it into (2-PDW, 10-PDW, 100-PDW, 110-PDW)

我的开发人员说:色标编号永远不能进行数字排序.我们需要为数据库中的所有色标添加另一个数字字段,然后对该字段进行数字编号.现在这些数字是按字母顺序排列的."

My developers say "The colorway number can never be sorted numerically. We would need to add another numeric field to the database for all the colorways and then sort that field numerically. Right now those numbers are in alphabetical order."

您如何用字母对数字进行排序?我们希望避免添加数字字段-这只是额外的工作.有没有新技术可以做到这一点?

How do you sort a numbers with letters? We'd like to avoid adding a Numeric Field - that's just extra work. Is there any new technique out to do this?

推荐答案

如果在scala中添加以下转换函数,则可以对所有字符串进行字母和数字排序:

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)

仅当您确定所有数字均低于9999时,此方法才有效.如果您有更多数字,则应考虑扩展功能或进行其他操作.

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.

这篇关于使用数字和字母对字母进行数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆