简体   繁体   中英

Build char from string

I want to allow a user specify a Unicode range via an XML config file. Eg they could state 0100..017F as the range. For my (Java) app to consume this char range, I need to convert the XML input (String) to type char. Any ideas?#

Eg

String input = "0100..017F"; // I can change format of input, if enables a solution
char from = '\u0100';
char to = '\u017f';

Thanks.

If it always matches exactly that format, then this will suffice:

char from = (char)Integer.parseInt(input.substring(0, 4), 16);
char to = (char)Integer.parseInt(input.substring(6), 16);

For something more flexible:

char from;
char to;
java.util.regex.Matcher m = java.util.regex.Pattern.compile(
    "^([\\da-fA-F]{1,4})(?:\\s*\\.\\.\\s*([\\da-fA-F]{1,4}))?$").matcher(input);
if (!m.find()) throw new IllegalArgumentException();
from = (char)Integer.parseInt(m.group(1), 16);
if (m.group(2) != null) {
    to = (char)Integer.parseInt(m.group(2), 16);
} else {
    to = from;
}

That allows for 1 to 4 hex digits for each character, the .. may have space around it, and the to part of the range may be omitted and assumed to be equal to from .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM