class UnitUtils {

    public static @Nullable Unit<?> parseUnit(@Nullable String pattern) {
        if (pattern == null || pattern.isBlank()) {
            return null;
        }

        String unitSymbol = pattern;
        int lastBlankIndex = pattern.lastIndexOf(" ");
        if (lastBlankIndex >= 0) {
            unitSymbol = pattern.substring(lastBlankIndex).trim();
        }

        if (!UNIT_PLACEHOLDER.equals(unitSymbol)) {
            if (UNIT_PERCENT_FORMAT_STRING.equals(unitSymbol)) {
                return SmartHomeUnits.PERCENT;
            }
            try {
                Quantity<?> quantity = Quantities.getQuantity("1 " + unitSymbol);
                return quantity.getUnit();
            } catch (IllegalArgumentException e) {
                // we expect this exception in case the extracted string does not match any known unit
                LOGGER.debug("Unknown unit from pattern: {}", unitSymbol);
            }
        }

        return null;
    }

}

class UnitUtilsTest {

    @Test
    public void testParsePureUnit() {

        assertThat(UnitUtils.parseUnit("DU"), is(SmartHomeUnits.DOBSON_UNIT));
        assertThat(UnitUtils.parseUnit("°F"), is(ImperialUnits.FAHRENHEIT));
        assertThat(UnitUtils.parseUnit("m"), is(SIUnits.METRE));
        assertThat(UnitUtils.parseUnit("%"), is(SmartHomeUnits.PERCENT));
    }

}