extract a substring in Java
I have the following string:
"hello this.is.a.test(MainActivity.java:47)"
and I want to be able to extract the MainActivity.java:47 (everything that is inside '(' and ')' and only the first occurance).
I tried with regex but 开发者_Go百科it seems that I am doing something wrong.
Thanks
You can do it yourself:
int pos1 = str.indexOf('(') + 1;
int pos2 = str.indexOf(')', pos1);
String result = str.substring(pos1, pos2)
Or you can use commons-lang which contains a very nice StringUtils
class that has substringBetween()
I think Regex is a liitle bit an overkill. I would use something like this:
String input = "hello this.is.a.test(MainActivity.java:47)";
String output = input.subString(input.lastIndexOf("(") + 1, input.lastIndexOf(")"));
This should work:
^[^\\(]*\\(([^\\)]+)\\)
The result is in the first group.
Another answer for your question :
String str = "hello this.is.a.test(MainActivity.java:47) another.test(MyClass.java:12)";
Pattern p = Pattern.compile("[a-z][\\w]+\\.java:\\d+", Pattern.CASE_INSENSITIVE);
Matcher m=p.matcher(str);
if(m.find()) {
System.out.println(m.group());
}
The RegExp explained :
[a-z][\w]+\.java:\d+
[a-z] > Check that we start with a letter ...
[\w]+ > ... followed by a letter, a digit or an underscore...
\.java: > ... followed exactly by the string ".java:"...
\d+ > ... ending by one or more digit(s)
Pseudo-code:
int p1 = location of '('
int p2 = location of ')', starting the search from p1
String s = extract string from p1 to p2
String.indexOf() and String.substring() are your friends.
Try this:
String input = "hello this.is.a.test(MainActivity.java:47) (and some more text)";
Pattern p = Pattern.compile("[^\\)]*\\(([^\\)]*)\\).*");
Matcher m = p.matcher( input );
if(m.matches()) {
System.out.println(m.group( 1 )); //output: MainActivity.java:47
}
This also finds the first occurence of text between ( and ) if there are more of them.
Note that in Java you normally have the expressions wrapped with ^
and $
implicitly (or at least the same effect), i.e. the regex must match the entire input string. Thus [^\\)]*
at the beginning and .*
at the end are necessary.
精彩评论