Reputation: 7788
I have the following string
ford-focus-albany-ny-v12356-l12205
I'm trying to parse the last two sets of numbers out
12356
and 12205
I'm using the prefix letter to define the id type since the order of those int may very.
v = vehicle id "id length may very"
l = location id "id length may very"
I'd also like to add one may exist without the other. Example
ford-focus-v12356
or albany-ny-l12205
I'm really not sure what the best approach to splitting the string dynamically is, my initial thought was to find the last two - and then try to parse the ints from the prefix. Anybody have any suggestions or a possible example?
Upvotes: 0
Views: 62
Reputation: 26
String str = "ford-focus-albany-ny-v12356-l12205";
String[] substrings = str.split("-");
for (String arg: substrings) {
if (arg.matches("v[0-9]*")) {
String v = arg.substring(1);
}
else if (arg.matches("l[0-9]*")) {
String l = arg.substring(1);
}
}
Upvotes: 1
Reputation: 726809
You can match one or both of them with a simple pattern:
(?:-([vl])(\\d+))(?:-[vl](\\d+))?
The idea behind this pattern is simple: it matches and captures the initial marker -v
or -l
, followed by a sequence of digits, which are captured into capturing groups.
Pattern p = Pattern.compile("(?:-([vl])(\\d+))(?:-[vl](\\d+))?");
for(String s : new String[] {"ford-focus-albany-ny-v12356-l12205","ford-focus-albany-ny-l12205","ford-focus-albany-ny-v12356"}) {
Matcher m = p.matcher(s);
if (m.find()) {
if (m.group(1).equals("v")) {
System.out.println("verhicle="+m.group(2));
String loc = m.group(3);
if (loc != null) {
System.out.println("location="+loc);
} else {
System.out.println("No location");
}
} else {
System.out.println("No vehicle");
System.out.println("location="+m.group(2));
}
}
}
Here is a demo on ideone.
Upvotes: 1
Reputation: 23381
You can try it with regex expression and replace like this:
//this will give you 12356
"ford-focus-albany-ny-v12356-l12205".replaceAll( "(.*)(-v)([^-]*)(.*)", "$3" );
//this will give you 12205
"ford-focus-albany-ny-v12356-l12205".replaceAll( "(.*)(-l)([^-]*)(.*)", "$3" );
//this will also give you 12356
"ford-focus-v12356".replaceAll( "(.*)(-v)([^-]*)(.*)", "$3" );
//this will give you 12205
"albany-ny-l12205".replaceAll( "(.*)(-l)([^-]*)(.*)", "$3" );
Upvotes: 1
Reputation: 709
How about trying to split with String.split("-")
and then use the Array returned like this:
String[] result = longString.split("-");
// Get the last number
String lastPrefix = result[result.lenght-1].subString(0, 1);
// Here check the prefix
// try to get number
int lastNumber;
try {
lastNumber = = Integer.parseInt(result[result.lenght-1].subString(1));
} catch (NumberFormatException e) {
// Do something with exception
}
// And now do similar with result.lenght-2
Upvotes: 0