Reputation: 657
I have the following code but it does not work. Not sure what is wrong here:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String ext_time = "23:24:25+26";
String short_time[] = ext_time.split("+");
System.out.print(short_time[0]);
}
}
I wanted to take string 23:24:25 out of 23:24:25+22. How would I do it?
Upvotes: 0
Views: 107
Reputation: 169
In split command '+' without escape will mean following :
'+' --> Occurs one or more times, is short for {1,} X+ - Finds one or several letter X
Please escape '+' character in your regex, Hence your new code will be
String short_time[] = ext_time.split("\\+");
Please refer following link for more details on split regex : http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Upvotes: 1
Reputation: 375
Firts is not a good name variable with brackets short_time[]
,
but ok, I runned your code and had: Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
'+' is a meta character of regEx, like bar or dot you have to escape it use ext_time.split("\\+");
Upvotes: 1
Reputation: 6437
You need to escape the +
character:
String short_time[] = ext_time.split("\\+");
Normally, the plus +
character is a quantifier in regex
, meaning at least one of the previous character/group
. So to split with the character, it needs to be escaped. And since the backslash\
is itself a special character, it needs to be escaped also. Thus, "\\+"
.
Upvotes: 4