Shasi
Shasi

Reputation: 274

Java String- How to get a part of package name in android?

Its basically about getting string value between two characters. SO has many questions related to this. Like:

How to get a part of a string in java?

How to get a string between two characters?

Extract string between two strings in java

and more. But I felt it quiet confusing while dealing with multiple dots in the string and getting the value between certain two dots.

I have got the package name as :

au.com.newline.myact

I need to get the value between "com." and the next "dot(.)". In this case "newline". I tried

Pattern pattern = Pattern.compile("com.(.*).");
Matcher matcher = pattern.matcher(beforeTask);
while (matcher.find()) {
        int ct = matcher.group();

I tried using substrings and IndexOf also. But couldn't get the intended answer. Because the package name in android varies by different number of dots and characters, I cannot use fixed index. Please suggest any idea.

Upvotes: 0

Views: 1737

Answers (5)

Pshemo
Pshemo

Reputation: 124275

As you probably know (based on .* part in your regex) dot . is special character in regular expressions representing any character (except line separators). So to actually make dot represent only dot you need to escape it. To do so you can place \ before it, or place it inside character class [.].

Also to get only part from parenthesis (.*) you need to select it with proper group index which in your case is 1.

So try with

String beforeTask = "au.com.newline.myact";
Pattern pattern = Pattern.compile("com[.](.*)[.]");
Matcher matcher = pattern.matcher(beforeTask);
while (matcher.find()) {
     String ct = matcher.group(1);//remember that regex finds Strings, not int
     System.out.println(ct);
}

Output: newline


If you want to get only one element before next . then you need to change greedy behaviour of * quantifier in .* to reluctant by adding ? after it like

Pattern pattern = Pattern.compile("com[.](.*?)[.]");
//                                          ^

Another approach is instead of .* accepting only non-dot characters. They can be represented by negated character class: [^.]*

Pattern pattern = Pattern.compile("com[.]([^.]*)[.]");

If you don't want to use regex you can simply use indexOf method to locate positions of com. and next . after it. Then you can simply substring what you want.

String beforeTask = "au.com.newline.myact.modelact";
int start = beforeTask.indexOf("com.") + 4; // +4 since we also want to skip 'com.' part
int end = beforeTask.indexOf(".", start); //find next `.` after start index 
String resutl = beforeTask.substring(start, end);
System.out.println(resutl);

Upvotes: 2

Christian Abella
Christian Abella

Reputation: 5797

I have done heaps of projects before dealing with websites scraping and I just have to create my own function/utils to get the job done. Regex might be an overkill sometimes if you just want to extract a substring from a given string like the one you have. Below is the function I normally use to do this kind of task.

private String GetValueFromText(String sText, String sBefore, String sAfter)
{      
  String sRetValue = "";
  int nPos = sText.indexOf(sBefore);
  if ( nPos > -1 )
  {
    int nLast = sText.indexOf(sAfter,nPos+sBefore.length()+1);
    if ( nLast > -1)
    {
      sRetValue = sText.substring(nPos+sBefore.length(),nLast);
    }
  }
  return sRetValue;
}

To use it just do the following:

String sValue = GetValueFromText("au.com.newline.myact", ".com.", ".");

Upvotes: 1

Kartik
Kartik

Reputation: 7917

private String getStringAfterComDot(String packageName) {
        String strArr[] = packageName.split("\\.");
        for(int i=0; i<strArr.length; i++){
            if(strArr[i].equals("com"))
                return strArr[i+1];
        }
        return "";
    }

Upvotes: 1

ucsunil
ucsunil

Reputation: 7494

All you have to do is split the strings by "." and then iterate through them until you find one that equals "com". The next string in the array will be what you want.

So your code would look something like:

String[] parts = packageName.split("\\.");
int i = 0;
for(String part : parts) {
    if(part.equals("com")
        break;
    }
    ++i;
}
String result = parts[i+1];

Upvotes: 2

almeynman
almeynman

Reputation: 7428

You can use reflections to get the name of any class. For example:

If I have a class Runner in com.some.package and I can run

Runner.class.toString() // string is "com.some.package.Runner"

to get the full name of the class which happens to have a package name inside.

TO get something after 'com' you can use Runner.class.toString().split(".") and then iterate over the returned array with boolean flag

Upvotes: 2

Related Questions