java - Reformatting a String with Particular Pattern -
i'm working on silly calendar widget work, , 1 of things i'm trying reformat how rooms/locations show up.
each conference room appears in 1 of following ways:
- dfw-d04-alpha (10)
- conf dfw alpha d04
- something totally different (like "meet @ desks")
the ideal format conference rooms representation this:
- alpha (dfw d4)
- in "totally different" case, preserve it
in example, dfw city (always 3 character abbreviation). d04 building/floor (d building, 4th floor). alpha actual "name" of conference room. , (10) capacity.
i've got implemented substrings , find replace determine format (if either) , rebuild in new format. , right now, it's extremely hard coded.
i feel should able in few lines of code. recommendations?
picking groups apart in scala (which uses java regex):
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 = else
where named groups comes in handy:
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: = alpha (dfw d04)
or add suffix group names if needed:
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
Comments
Post a Comment