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


its getting string value between 2 characters. has many questions related this. like:

how part of string in java?

how string between 2 characters?

extract string between 2 strings in java

and more. felt quiet confusing while dealing multiple dots in string , getting value between 2 dots.

i have got package name :

au.com.newline.myact 

i need value between "com." , next "dot(.)". in case "newline". tried

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

i tried using substrings , indexof also. couldn't intended answer. because package name in android varies different number of dots , characters, cannot use fixed index. please suggest idea.

as know (based on .* part in regex) dot . special character in regular expressions representing character (except line separators). make dot represent dot need escape it. can place \ before it, or place inside character class [.].

also part parenthesis (.*) need select proper group index in case 1.

so try

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 regex finds strings, not int      system.out.println(ct); } 

output: newline


if want 1 element before next . need change greedy behaviour of * quantifier in .* reluctant adding ? after like

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

another approach instead of .* accepting non-dot characters. can represented negated character class: [^.]*

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

if don't want use regex can use indexof method locate positions of com. , next . after it. can substring want.

string beforetask = "au.com.newline.myact.modelact"; int start = beforetask.indexof("com.") + 4; // +4 since want skip 'com.' part int end = beforetask.indexof(".", start); //find next `.` after start index  string resutl = beforetask.substring(start, end); system.out.println(resutl); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -