java - Unformat formatted String -


i have simple formatted string:

double d = 12.348678; int = 9876; string s = "abcd"; system.out.printf("%08.2f%5s%09d", d, s, i);  // %08.2f = '12.348678' -> '00012,35' // %5s = 'abcd' -> ' abcd' // %09d = '9876' -> '000009876' // %08.2f%5s%09d = '00012,35 abcd000009876' 

when know pattern: %08.2f%5s%09d , string: 00012,35 abcd000009876: can "unformat" string in way?

eg. expected result 3 tokens: '00012,35', ' abcd', '000009876'

this specific pattern. general parser formatstring, (because call unformatting parsing) different.

public class unformat {      public static integer getwidth(pattern pattern, string format) {         matcher matcher = pattern.matcher(format);         if (matcher.find()) {             return integer.valueof(matcher.group(1));         }         return null;     }      public static string getresult(pattern p, string format, string formatted,             integer start, integer width) {         width = getwidth(p, format);         if (width != null) {             string result = formatted.substring(start, start + width);             start += width;             return result;         }         return null;     }      public static void main(string[] args) {         string format = "%08.2f%5s%09d";         string formatted = "00012.35 abcd000009876";         string[] formats = format.split("%");          list<string> result = new arraylist<string>();         integer start = 0;         integer width = 0;          (int j = 1; j < formats.length; j++) {             if (formats[j].endswith("f")) {                 pattern p = pattern.compile(".*([0-9])+\\..*f");                 result.add(getresult(p, formats[j], formatted, start, width));             } else if (formats[j].endswith("s")) {                 pattern p = pattern.compile("([0-9])s");                 result.add(getresult(p, formats[j], formatted, start, width));             } else if (formats[j].endswith("d")) {                 pattern p = pattern.compile("([0-9])d");                 result.add(getresult(p, formats[j], formatted, start, width));             }         }         system.out.println(result);     }  } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -