Java parsing formatted string

Parse strings and convert the value to .java types

I should also give some usage examples. Use the below static method for simple usage (only supports the default java types):

Integer i1 = StringToTypeParser.parse(" 1", Integer.class); int i2 = StringToTypeParser.parse("2", int.class); float f = StringToTypeParser.parse("2.2", float.class); Number n = StringToTypeParser.parse("2.2", float.class); MyEnum a = StringToTypeParser.parse("BBB", MyEnum.class); File file = StringToTypeParser.parse("/path/to", File.class); Boolean b1 = StringToTypeParser.parse("true", Boolean.class); boolean b2 = StringToTypeParser.parse("0", Boolean.class); 

Or if you want to register your own TypeParsers, build your own StringToTypeParser instance (which by default supports the java types) as follow:

StringToTypeParser parser = StringToTypeParser.newBuilder() .registerTypeParser(new CarTypeParser()) .registerTypeParser(int.class, new MySpecialIntTypeParser()) .build(); Car volvo = parser.parseType("volvo", Car.class); 

Edit: after comments from review:

Thanks for the great comments in the answer! Below are the final outcome of the changes made. The Util.java class is now removed, so is also all the reflection code, which makes a much nicer/cleaner code.

The TypeParser interface remains the same

package com.github.drapostolos.typeparser; public interface TypeParser

Replaced the static inner classes with anonymous classes instead.

package com.github.drapostolos.typeparser; import java.io.File; import java.util.HashMap; import java.util.Map; class DefaultTypeParsers < private DefaultTypeParsers() < new AssertionError("Not meant for instantiation"); >private static final String BOOLEAN_ERROR_MESSAGE = "\"%s\" is not parsable to a Boolean."; private static final String CHARACTER_ERROR_MESSAGE = "\"%s\" must only contain a single character."; private static final Map, TypeParser> DEFAULT_TYPE_PARSERS = new HashMap, TypeParser>(); private static final Map, Class> WRAPPER_TO_PRIMITIVE = new HashMap, Class>(); static Map, TypeParser> copy() < return new HashMap, TypeParser>(DEFAULT_TYPE_PARSERS); > static < WRAPPER_TO_PRIMITIVE.put(Boolean.class, boolean.class); WRAPPER_TO_PRIMITIVE.put(Byte.class, byte.class); WRAPPER_TO_PRIMITIVE.put(Short.class, short.class); WRAPPER_TO_PRIMITIVE.put(Character.class, char.class); WRAPPER_TO_PRIMITIVE.put(Integer.class, int.class); WRAPPER_TO_PRIMITIVE.put(Long.class, long.class); WRAPPER_TO_PRIMITIVE.put(Float.class, float.class); WRAPPER_TO_PRIMITIVE.put(Double.class, double.class); >private static void put(Class type, TypeParser typeParser) < DEFAULT_TYPE_PARSERS.put(type, typeParser); if(WRAPPER_TO_PRIMITIVE.containsKey(type))< // add primitive targetType if existing, example int.class, boolean.class etc. ClassprimitiveType = WRAPPER_TO_PRIMITIVE.get(type); DEFAULT_TYPE_PARSERS.put(primitiveType, typeParser); > > static< put(Boolean.class, new TypeParser() < @Override public Boolean parse(final String value0) < String value = value0.trim().toLowerCase(); if(value.equals("true"))< return Boolean.TRUE; >else if(value.equals("false")) < return Boolean.FALSE; >throw new IllegalArgumentException(String.format(BOOLEAN_ERROR_MESSAGE, value0)); > >); put(Character.class, new TypeParser() < @Override public Character parse(String value) < if(value.length() == 1)< return Character.valueOf(value.charAt(0)); >throw new IllegalArgumentException(String.format(CHARACTER_ERROR_MESSAGE, value)); > >); put(Byte.class, new TypeParser() < @Override public Byte parse(String value) < return Byte.valueOf(value.trim()); >>); put(Integer.class, new TypeParser() < @Override public Integer parse(String value) < return Integer.valueOf(value.trim()); >>); put(Long.class, new TypeParser() < @Override public Long parse(String value) < return Long.valueOf(value.trim()); >>); put(Short.class, new TypeParser() < @Override public Short parse(String value) < return Short.valueOf(value.trim()); >>); put(Float.class, new TypeParser() < @Override public Float parse(String value) < return Float.valueOf(value); >>); put(Double.class, new TypeParser() < @Override public Double parse(String value) < return Double.valueOf(value); >>); put(File.class, new TypeParser() < @Override public File parse(String value) < return new File(value.trim()); >>); put(String.class, new TypeParser() < @Override public String parse(String value) < return value; >>); > > 

Removed the static StringToTypeParser.parse(. ) method for simplicity.

package com.github.drapostolos.typeparser; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public final class StringToTypeParser < private static final Object STATIC_METHOD = null; private final Map, TypeParser> typeParsers; public static StringToTypeParserBuilder newBuilder() < return new StringToTypeParserBuilder(); >StringToTypeParser(Map, TypeParser> typeParsers) < this.typeParsers = Collections.unmodifiableMap(new HashMap, TypeParser>(typeParsers)); > public T parse(String value, Class type) < if (value == null) < throw new NullPointerException(nullArgumentErrorMsg("value")); >if (type == null) < throw new NullPointerException(nullArgumentErrorMsg("type")); >// convert "null" string to null type. if (value.trim().equalsIgnoreCase("null")) < if (type.isPrimitive()) < String message = "'%s' primitive can not be set to null."; throw new IllegalArgumentException(String.format(message, type.getName())); >return null; > Object result = null; if (typeParsers.containsKey(type)) < result = callTypeParser(value, type); >else if ((result = callFactoryMethodIfExisting("valueOf", value, type)) != null) < // >else if ((result = callFactoryMethodIfExisting("of", value, type)) != null) < // >else < String message = "There is no registered 'TypeParser' for that type, or that " + "type does not contain one of the following static factory methods: " + "'%s.valueOf(String)', or '%s.of(String)'."; message = String.format(message, type.getSimpleName(), type.getSimpleName()); message = canNotParseErrorMsg(value, type, message); throw new IllegalArgumentException(message); >/* * This cast is correct, since all above checks ensures we're casting to * the right type. */ @SuppressWarnings("unchecked") T temp = (T) result; return temp; > /** * This method is static because it is also called from . */ static String nullArgumentErrorMsg(String argName) < return String.format("Argument named '%s' is illegally set to null!", argName); >private Object callTypeParser(String value, Class type) < try < return typeParsers.get(type).parse(value); >catch (NumberFormatException e) < String message = canNotParseErrorMsg(value, type, numberFormatErrorMsg(e)); throw new IllegalArgumentException(message, e); >catch (RuntimeException e) < throw new IllegalArgumentException(canNotParseErrorMsg(value, type, e.getMessage()), e); >> private String numberFormatErrorMsg(NumberFormatException e) < return String.format("Number format exception %s.", e.getMessage()); >private String canNotParseErrorMsg(String value, Class type, String message) < return String.format("Can not parse \"%s\" to type '%s' due to: %s", value, type.getName(), message); >private Object callFactoryMethodIfExisting(String methodName, String value, Class type) < Method m; try < m = type.getDeclaredMethod(methodName, String.class); m.setAccessible(true); if (!Modifier.isStatic(m.getModifiers())) < // Static factory method does not exists, return null return null; >> catch (Exception e) < // Static factory method does not exists, return null return null; >try < if(type.isEnum())< value = value.trim(); >return m.invoke(STATIC_METHOD, value); > catch (InvocationTargetException e) < // filter out the InvocationTargetException stacktrace/message. throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), e.getCause()); >catch (Throwable t) < throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), t); >> private String makeErrorMsg(String methodName, String value, Class type) < String methodSignature = String.format("%s.%s('%s')", type.getName(), methodName, value); String message = " Exception thrown in static factory method '%s'. See underlying " + "exception for additional information."; return canNotParseErrorMsg(value, type, String.format(message, methodSignature)); >> 

Removed registerTypeParser(TypeParser) method, which allowed for removing reflection code.

package com.github.drapostolos.typeparser; import java.util.Map; public final class StringToTypeParserBuilder < private Map, TypeParser> typeParsers; StringToTypeParserBuilder() < // Initialize with the default typeParsers typeParsers = DefaultTypeParsers.copy(); >public StringToTypeParserBuilder unregisterTypeParser(Class type) < if(type == null) < throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("type")); >typeParsers.remove(type); return this; > public StringToTypeParserBuilder registerTypeParser(Class type, TypeParser typeParser) < if(typeParser == null) < throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("typeParser")); >if(type == null) < throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("type")); >typeParsers.put(type, typeParser); return this; > public StringToTypeParser build() < return new StringToTypeParser(typeParsers); >> 

Источник

Java Parse String

Java Parse String

Parsing String in java is known as converting data in the String format from a file, user input, or a certain network. Parsing String is the process of getting information that is needed in the String format. String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class.

Web development, programming languages, Software testing & others

String parsing can also be done through StringTokenizer. StringTokenizer class allows its constructor to break the String into tokens. StringTokenizer is much simpler than other classes. StringTokenizer is a legacy class, so everyone must avoid the use of this class.

String strMsg = "An Example of String"; String delims = "[delimiters]+"; String tokenString = strMsg.split(delims);

In the above syntax, multiple delimiter can be used inside the square brackets. “+” sign after bracket treats multiple delimiter as a single delimiter.

Initialization of Parse String

In java, a String can be converted into char, Object, int, date, time, etc. String parsing is initialized by a certain java class method as per the data type is required.

Example #1

In this example, we can see how String is parsing into different types of formats like date & integer. Similarly, we can use other methods to convert a string into other formats.

import java.text.SimpleDateFormat; import java.util.Date; public class StringParsingInDiffTypeExample < public static void main(String[] args)throws Exception < System.out.println("String parsing into Date Oject : \n"); String strDate1 = "12/01/2020"; String strDate2 = "12-Jan-2020"; String strDate3 = "Sun, Jan 12 2020"; //converting date format into the date object here SimpleDateFormat strFormat1 = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat strFormat2 = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat strFormat3 = new SimpleDateFormat("E, MMM dd yyyy"); //date retrieving here after parsing through parse method Date dateObj1 = strFormat1.parse(strDate1); Date dateObj2 = strFormat2.parse(strDate2); Date dateObj3 = strFormat3.parse(strDate3); //printing here the date as a char System.out.println("Date String 1 = " + strDate1 + "\t Date Object 1 = " + dateObj1); System.out.println("Date String 2 = " + strDate2 + "\t Date Object 2 = " + dateObj2); System.out.println("Date String 3 = " + strDate3 + "\t Date String 3 = " + dateObj3); System.out.println("\n\nString parsing into integer : \n"); String strVal1 = "50"; String strVal2 = "1000"; String strVal3 = "20000"; //Converting String into int using parseInt() int intValue1 = Integer.parseInt(strVal1); int intValue2 = Integer.parseInt(strVal2); int intValue3 = Integer.parseInt(strVal3); //Printing integer value System.out.println(intValue1); System.out.println(intValue2); System.out.println(intValue3); >>

Output for the above-given program is given below; we can see how String is converted into different data type by using different methods.

java parse string 1

Example #2

In this example, using the split method for parsing of the string to array format.

public class SplitMethodExample < public static void main(String args[])< System.out.println("String Parsing Example #1 :\n"); //In this example one space character is used as a delimiter String str1 = new String("Nothing is impossible in the world!"); String delimSpace = " "; String[] arr1 = str1.split(delimSpace); for (String uniqVal1 : arr1) < System.out.println(uniqVal1); >System.out.println("\n\nString Parsing Example #2 :\n"); //In this example a comma is used as a delimiter String str2 = new String("Alabama,California,texas,30,78"); String delimsComma = "[,]+"; String[] arr2 = str2.split(delimsComma); for (String uniqVal2 : arr2) < System.out.println(uniqVal2); >System.out.println("\n\nString Parsing Example #3 :\n"); //In this example multiple delimiter is used used as a delimiter String str3 = new String("Many of the people always say without thinking ,do you know ?Possibly Not!"); String delims = "[. ]+"; String[] arr3 = str3.split(delims); for (String uniqVal3 : arr3) < System.out.println(uniqVal3); >> >

The above given an example contains three sections, all the three-section using the different delimiter for parsing the String. In the below-given screenshot, we can see the output of the above-given program.

java parse string 2

Example #3

In this example, the StringTokenizer class is used for parsing. The StringTokenizer class’s constructor takes two parameters: the first one is the string & the second one is the delimiter. This class contains some methods, i.e. hasMoreElements() to check whether the next index holding any value or not while nextElement() returns the value at the next index.

import java.util.StringTokenizer; public class StringTokenizerParsingExample < public static void main(String[] args) < System.out.println("StringTokenizer Parsing Example: \n"); String strText = "Kansas,Louisiana,Maryland,Massachusetts,Mississippi,New Jersey"; String delims = ","; StringTokenizer stObj = new StringTokenizer(strText, delims); //Iterating here for the next element while (stObj.hasMoreElements()) < System.out.println("StringTokenizer Output: " + stObj.nextElement()); >> >

Output:

example 3

The above parsing output is given below; we can see how comma-separated values are listed in the next column.

Example #4

This example shows how the indexOf method can be used effectively to parse any String in java. In this program, a String in the middle of the sentence is being converted to uppercase.

public class StringParsingExample < public static void main(String args[])< String strPara = "The Paragraph needs additional citations for [verification]"; int openIndex = strPara.indexOf("["); int closedIndex = strPara.indexOf("]"); // extracting here the String inside of the square bracket String subString = strPara.substring(openIndex+1, closedIndex); //converting substring in the uppercase which is inside of subString= subString.toUpperCase(); // concating here all the substrings String modifiedPara = strPara.substring(0, openIndex + 1) + subString + strPara.substring(closedIndex); System.out.println(modifiedPara); >>

Output: Output of the above-given program is given below.

example4

Example #5

In this example, we can see how a string is converted into an array of chars.

public class StringParsingCharExample < public static void main(String[] args) < String strText = "Australia"; char[] charArr = strText.toCharArray(); System.out.println(charArr.length); char secondPosChar = strText.charAt(2); System.out.println(secondPosChar); char[] charSet = new char[9]; strText.getChars(0, 9, charSet, 0); for (char uniqChar : charSet) < System.out.println(uniqChar); >> >

Output:
The Output for the above-given program is given below.

In the attached output screenshot, we can see how a String is converted into the array of characters by using methods toCharArray().

Conclusion – Java Parse String

In the above-given Article, we have gone through the parsing, String parsing in Java, etc. How the split method plays a role in parsing the data type. Some other ways are also available which can be used for parsing, such as StringTokenizer.

This has been a guide to Java Parse String. Here we discuss the syntax and initialization of the Java Parse String. you may also have a look at the following articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Читайте также:  Collections tree in java
Оцените статью