How to get substring based on special characters in android? - java

Actually this is a very simple question, I tried a lot but I am unable to get the exact solution. I have a string like:
String mystring = "one<1234567>,two<98765432>,three<878897656>";
Here I want the data which is inside "<" and ">". Can anyone help me with this?

I would use regex
String str = "one<1234567>,two<98765432>,three<878897656>";
Matcher m = Pattern.compile("<(.+?)>").matcher(str);
while(m.find()) {
String v = m.group(1);
}

Try
String mystring = "one<1234567>,two<98765432>,three<878897656>";
String[] result = mystring.split(",");
for (String s : result) {
s = s.substring(s.indexOf("<")+1);
s = s.substring(0, s.indexOf(">"));
System.out.println(s);
}
Print result :
1234567
98765432
878897656

You can use a regex like <(.*?)> :
String mystring = "one<1234567>,two<98765432>,three<878897656>";
Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher(mystring);
while (matcher.find())
{
System.out.println(matcher.group(1));
}

Try this
String mystring = "one<1234567>,two<98765432>,three<878897656>";
String[] a = myString.split(",");
for(int i = 0; i < a.length; i++){
String substr=a[i].subString(a[i].indexOf("<"),a[i].indexOf(">"));
System.out.println(substr);
}

Try if your inner bracket value always numeric and outside alphabetical i.e. <, >
String[] strings=mystring.replaceAll("[a-z<>]", "").split(",");
for(String string:stringsArray)
{
System.out.println(string);
}

i found an new solution from StringTokenizer class
you can use it as,
StringTokenizer tokens = new StringTokenizer(KEY_SUBFOLDERNAME, ".");
String first_string = tokens.nextToken();
File_Ext = tokens.nextToken();
System.out.println("First_string : "+first_string);
System.out.println("File_Ext : "+File_Ext);

Related

find overlapping regex pattern

I'm using regex to find a pattern
I need to find all matches in this way :
input :"word1_word2_word3_..."
result: "word1_word2","word2_word3", "word4_word5" ..
It can be done using (?=) positive lookahead.
Regex: (?=(?:_|^)([^_]+_[^_]+))
Java code:
String text = "word1_word2_word3_word4_word5_word6_word7";
String regex = "(?=(?:_|^)([^_]+_[^_]+))";
Matcher matcher = Pattern.compile(regex).matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output:
word1_word2
word2_word3
word3_word4
...
Code demo
You can do it without regex, using split:
String input = "word1_word2_word3_word4";
String[] words = input.split("_");
List<String> outputs = new LinkedList<>();
for (int i = 0; i < words.length - 1; i++) {
String first = words[i];
String second = words[i + 1];
outputs.add(first + "_" + second);
}
for (String output : outputs) {
System.out.println(output);
}

How do you add a delimiter in a given String format in Java?

I have the following String
"12:00:00, 2:30:003:45:00,23:45:00";
I have to update the string to use the following format:
"12:00:00, 2:30:00 |3:45:00,23:45:00 ";
I am able to split each string, but I do not know how to generate the required format. Here is the code I've written so far:
final String s = "12:00:00, 2:30:003:45:00,23:45:00";
final Pattern p = Pattern.compile("\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher m = p.matcher(s);
final List<String> tokens = new ArrayList<String>();
while (m.find()) {
tokens.add(m.group(1));
}
for (String tok : tokens) {
System.out.printf("[%s]%n", tok);
}
How about this:
final String string = "12:00:00, 2:30:003:45:00,23:45:00";
final Pattern pattern = Pattern.compile("\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher matcher = pattern.matcher(string);
final List<String> tokens = new ArrayList<String>();
while (matcher.find()) {
tokens.add(matcher.group(1));
}
System.out.println("tokens = " + tokens);
StringBuilder formattedString = new StringBuilder();
formattedString.append(tokens.get(0));
for (int i = 1; i < tokens.size(); i++) {
if (i % 2 == 0) {
formattedString.append(" | ");
} else {
formattedString.append(", ");
}
formattedString.append(tokens.get(i));
}
System.out.println(formattedString);
Edit: I've updated it to use a for loop when constructing the formatted string based on the comments I've read.
If you want to add | after two dates separated by comma your code can look like
final String s = "12:00:00, 2:30:003:45:00,23:45:00";
final Pattern p = Pattern.compile("(\\d+:\\d\\d:\\d\\d)\\s*,\\s*(\\d+:\\d\\d:\\d\\d)");
final Matcher m = p.matcher(s);
String result = m.replaceAll("$0|");
Or even
String result = s.replaceAll("?:\\d+:\\d\\d:\\d\\d),\\s*(?:\\d+:\\d\\d:\\d\\d)","$0|");
$0 refers to group 0 which holds entire match.
result is 12:00:00, 2:30:00|3:45:00,23:45:00|
You may consider this replaceAll method using lookarounds:
final String s = "12:00:00, 2:30:003:45:00,23:45:00";
System.out.printf("%s%n", s.replaceAll("(?<=:\\d\\d)(?=(?::\\d{1,2}|$))", "|"));
// 12:00|:00, 2:30|:003:45|:00,23:45|:00|

ReplaceFirst with Regular Expression

Let's say I have a String
String link = "www.thisisalink.com/tick1=#tick1#&tick2=#tick2#&tick3=#tick3#&tick4=#tick4#";
Then I can use
link = replaceFirst("(.+)=#\\1#", "");
To make it
link = "www.thisisalink.com/&tick2=#tick2#&tick3=#tick3#&tick4=#tick4#";
But I want to loop though the String, to get what has been replace and save it somewhere else, like a linked list or an array... result would be:
String[] result = ["tick1=#tick1#", "tick2=#tick2#", "tick3=#tick3#", "tick4=#tick4#"];
String link = "www.thisisalink.com/&&&";
But how can I do this? I tried looping with
while (link.matches("(.+)=#\\1#")){}
Which didn't work.
You can use Pattern Matcher classes to iterate over your string to find substrings that will match your regex. Then to replace founded substring you can use appednReplacement and appendTail. To get founded match you can use group() from Matcher instance.
Here is something similar to what you want
String link = "www.thisisalink.com/tick1=#tick1#&tick2=#tick2#&tick3=#tick3#&tick4=#tick4#";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("(.+)=#\\1#");
Matcher m = p.matcher(link);
List<String> replaced = new ArrayList<>();
while (m.find()) {
m.appendReplacement(sb, "");
replaced.add(m.group());
}
m.appendTail(sb);
//to replace link with String stored in sb use link=sb.toString();
//otherwise link will be unchanged
System.out.println(sb);
System.out.println(replaced);
output:
www.thisisalink.com/&&&
[tick1=#tick1#, tick2=#tick2#, tick3=#tick3#, tick4=#tick4#]
This produces the Strings you want:
public static void main(String[] args)
{
final String link = "www.thisisalink.com/tick1=#tick1#&tick2=#tick2#&tick3=#tick3#&tick4=#tick4#";
final int index = link.indexOf("/") + 1;
final String[] result = link.substring(index).split("&");
final String newLink = link.substring(0, index) + repeat("&", result.length -1);
System.out.println(newLink);
for(final String tick : result)
{
System.out.println(tick);
}
}
private static String repeat(final String toRepeat, final int repetitions)
{
final StringBuilder sb = new StringBuilder(repetitions);
for(int i = 0; i < repetitions; i++)
{
sb.append(toRepeat);
}
return sb.toString();
}
Produces:
www.thisisalink.com/&&&
tick1=#tick1#
tick2=#tick2#
tick3=#tick3#
tick4=#tick4#

Java, How to split String with shifting

How can I split a string by 2 characters with shifting.
For example;
My string is = todayiscold
My target is: "to","od","da","ay","yi","is","sc","co","ol","ld"
but with this code:
Arrays.toString("todayiscold".split("(?<=\\G.{2})")));
I get: `"to","da","yi","co","ld"
anybody helps?
Try this:
String e = "example";
for (int i = 0; i < e.length() - 1; i++) {
System.out.println(e.substring(i, i+2));
}
Use a loop:
String test = "abcdefgh";
List<String> list = new ArrayList<String>();
for(int i = 0; i < test.length() - 1; i++)
{
list.add(test.substring(i, i + 2));
}
Following regex based code should work:
String str = "todayiscold";
Pattern p = Pattern.compile("(?<=\\G..)");
Matcher m = p.matcher(str);
int start = 0;
List<String> matches = new ArrayList<String>();
while (m.find(start)) {
matches.add(str.substring(m.end()-2, m.end()));
start = m.end()-1;
}
System.out.println("Matches => " + matches);
Trick is to use end()-1 from last match in the find() method.
Output:
Matches => [to, od, da, ay, yi, is, sc, co, ol, ld]
You cant use split in this case because all split does is find place to split and brake your string in this place, so you cant make same character appear in two parts.
Instead you can use Pattern/Matcher mechanisms like
String test = "todayiscold";
List<String> list = new ArrayList<String>();
Pattern p = Pattern.compile("(?=(..))");
Matcher m = p.matcher(test);
while(m.find())
list.add(m.group(1));
or even better iterate over your Atring characters and create substrings like in D-Rock's answer

how to get the value after certain Prefix in android?

I have a string like abc-5,xyz-9,pqr-15 Now,I want to get the value only after "-" So, how can i get that value..and i want this value in String Array?
You can try
String string = "abc-5,xyz-9,pqr-15";
String[] parts = string.split(",");
String val1 = parts[0].split("-");
.....
and so on
int pos = string.indexOf('-');
String sub = string.substring(pos);
If you have multiple values in each string, you'll have to split it first (using split method). For example:
String[] array = string.split(',');
String[] values = new String[array.length];
for(int i = 0; i < array.length; i++)
values[i] = array[i].substring(arrays[i].indexOf('-'));
Now you have the values in an array.
I would use split on your string.
String str = "abc-5,xyz-9,pqr-15";
String[] arr = str.split(",");
for (String elem: arr) {
System.out.print(elem.split("-")[1] + " : "); // Will print - `5 : 9 : 15`
}
or with Regular Expression like this: -
Matcher matcher = Pattern.compile("-(\\d+)").matcher(str);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
Use:
String newString= oldString.substring(oldString.indexOf('-'));

Categories