gpt4 book ai didi

java - 使用特定模式重新格式化字符串

转载 作者:行者123 更新时间:2023-12-01 12:38:24 24 4
gpt4 key购买 nike

我正在开发一个愚蠢的日历小部件来工作,我想做的事情之一就是重新格式化房间/位置的显示方式。

每个 session 室以下列方式之一显示:

  • DFW-D04-Alpha (10)
  • Conf DFW Alpha D04
  • 完全不同的东西(例如“Meet @ Desks”)

session 室表示的理想格式是:

  • 阿尔法 (DFW D4)
  • 在“完全不同”的情况下,保留它即可

在此示例中,DFW 是城市(始终是 3 个字符的缩写)。 D04 是大楼/楼层(D 楼 4 楼)。 Alpha 是 session 室的实际“名称”。 (10) 为其容量。

我目前已经使用子字符串实现了它,并查找替换以确定它是哪种格式(如果有的话),然后以新格式重建它。现在,它的编码非常硬。

我觉得我应该能够只用几行代码就可以做到这一点。有什么建议吗?

最佳答案

在 Scala 中将组分开(使用 Java 正则表达式):

scala> val r = """(\w{3})-(\p{Alpha})(\d+)-(\w+) \(\d+\)|Conf (\w{3}) (\w+) (\p{Alpha})(\d+)|(.+)""".r

scala> def f(s: String) = s match { case r(city, bld, flr, name, _*) if city != null => s"$name ($city $bld${flr.toInt})"
| case r(_, _, _, _, city, name, bld, flr, _*) if city != null => s"$name ($city $bld${flr.toInt})" case x => x }
f: (s: String)String

scala> f("Conf DFW Alpha D04")
res8: String = Alpha (DFW D4)

scala> f("DFW-D04-Alpha (10)")
res9: String = Alpha (DFW D4)

scala> f("Something else")
res10: String = Something else

命名组派上用场的地方:

scala> val r = """(?<city>\w{3})-(?<bld>\p{Alpha}\d+)-(?<name>\w+) \(\d+\)|Conf (?<city2>\w{3}) (?<name2>\w+) (?<bld2>\p{Alpha}\d+)|(.+)""".r
r: scala.util.matching.Regex = (?<city>\w{3})-(?<bld>\p{Alpha}\d+)-(?<name>\w+) \(\d+\)|Conf (?<city2>\w{3}) (?<name2>\w+) (?<bld2>\p{Alpha}\d+)|(.+)

scala> val m = r.pattern matcher "DFW-D04-Alpha (10)"
m: java.util.regex.Matcher = java.util.regex.Matcher[pattern=(?<city>\w{3})-(?<bld>\p{Alpha}\d+)-(?<name>\w+) \(\d+\)|Conf (?<city2>\w{3}) (?<name2>\w+) (?<bld2>\p{Alpha}\d+)|(.+) region=0,18 lastmatch=]

scala> if (m.matches && m.group("city") != null) "%s (%s %s)".format(m.group("name"), m.group("city"), m.group("bld"))
res16: Any = Alpha (DFW D04)

或者根据需要为组名称添加后缀:

scala> val gs = List("name", "city", "bld")
gs: List[String] = List(name, city, bld)

scala> val r = """(?<city>\w{3})-(?<bld>\p{Alpha}\d+)-(?<name>\w+) \(\d+\)|Conf (?<city2>\w{3}) (?<name2>\w+) (?<bld2>\p{Alpha}\d+)|(?<other>.+)""".r
r: scala.util.matching.Regex = (?<city>\w{3})-(?<bld>\p{Alpha}\d+)-(?<name>\w+) \(\d+\)|Conf (?<city2>\w{3}) (?<name2>\w+) (?<bld2>\p{Alpha}\d+)|(?<other>.+)

scala> def f(s: String) = {
| val m = r.pattern matcher s
| if (!m.matches) "" else Option(m group "other") getOrElse {
| val ns = if (m.group("city") == null) gs map (_ + "2") else gs
| "%s (%s %s)".format(ns map m.group : _*)
| }}
f: (s: String)String

scala> f("DFW-D04-Alpha (10)")
res20: String = Alpha (DFW D04)

scala> f("Conf DFW Alpha D04")
res21: String = Alpha (DFW D04)

scala> f("other")
res22: String = other

关于java - 使用特定模式重新格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com