Parsing strings in java

What is the best way to do the following in Java. I have two input lines

this is a good example with 234 songs this is %%type%% example with %%number%% songs 

I need to extract the type and number from a string.

The answer in this case is type = "a good" and number = "234"

thanks

+4
source share
4 answers

You can do this with regular expressions:

 import java.util.regex.*; class A { public static void main(String[] args) { String s = "this is a good example with 234 songs"; Pattern p = Pattern.compile("this is a (.*?) example with (\\d+) songs"); Matcher m = p.matcher(s); if (m.matches()) { String kind = m.group(1); String nbr = m.group(2); System.out.println("kind: " + kind + " nbr: " + nbr); } } } 
+7
source

Java has regular expressions :

 Pattern p = Pattern.compile("this is (.+?) example with (\\d+) songs"); Matcher m = p.matcher("this is a good example with 234 songs"); boolean b = m.matches(); 
+3
source

if the second line is a pattern. you can compile it in regexp for example

 String in = "this is a good example with 234 songs"; String pattern = "this is %%type%% example with %%number%% songs"; Pattern p = Pattern.compile(pattern.replaceAll("%%(\w+)%%", "(\\w+)"); Matcher m = p.matcher(in); if (m.matches()) { for (int i = 0; i < m.groupsCount(); i++) { System.out.println(m.group(i+1)) } } 

If you need named groups, you can also parse your line pattern and save the mapping between the group index and the name on the Map.

+1
source

Geos, I would recommend using the Apache Velocity library http://velocity.apache.org/ . This is a template for strings. You, for example, will look like

 this is a good example with 234 songs this is $type example with $number songs 

The code for this will look like

 final Map<String,Object> data = new HashMap<String,Object>(); data.put("type","a good"); data.put("number",234); final VelocityContext ctx = new VelocityContext(data); final StringWriter writer = new StringWriter(); engine.evaluate(ctx, writer, "Example templating", "this is $type example with $number songs"); writer.toString(); 
0
source

Source: https://habr.com/ru/post/1301260/


All Articles