I have a string and want to sub-string till 3rd occurrence of "," . I can achieve this using Array. here is the code
String test ="hi,this,is,a,string.";
String[] testArray = test.split(",");
System.out.println(testArray[0]+","+testArray[1]+","+testArray[2]);
Output is :- hi,this,is
Is there anyway to achieve the same using "substring(0, text.indexOf(","))" method.Second thing is there could be some instances where there is no "," in the string and i want to handle both scenarios
Thanks in advance
I'm not sure if I really recommend this, but — yes; there's a two-arg overload of indexOf that lets you specify the starting position to search at; so you can write:
final int firstCommaIndex = test.indexOf(',');
final int secondCommaIndex = test.indexOf(',', firstCommaIndex + 1);
final int thirdCommaIndex = test.indexOf(',', secondCommaIndex + 1);
System.out.println(test.substring(0, thirdCommaIndex));
So what you are looking for is basically a way to receive the n-th (3rd) index of a char (,) in your String.
While there is no functionality for that in Java's Standard library, you can either create your own construct (which could look like this answer),
or alternatively you could use StringUtils from Apache, making your desired solution look smth like this:
String test ="hi,this,is,a,string.";
int index = StringUtils.ordinalIndexOf(test, ",", 3);
String desired = test.substring(0, index);
System.out.println(desired);
Other way with stream java 8. This can handle both of your scenarios
System.out.println(Stream.of(test.split(",")).limit(3).collect(Collectors.joining(",")));
You can use regex to achieve this:
import java.util.regex.*;
public class TestRegex {
public static void main(String []args){
String test = "hi,this,is,a,string.";
String regex = "([[^,].]+,?){3}(?=,)";
Pattern re = Pattern.compile(regex);
Matcher m = re.matcher(test);
if (m.find()) {
System.out.println(m.group(0));
}
}
}
Related
I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.
I have the next String in java:
|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|
So I need to replace the value |50200| (second one) with other value according to some decisions,but only need to replace the second one, how can I do, since replace or replaceAll don't work in this case. I was trying with some regex and appendReplacement but it did not work,also I need it to be as quick as possible, code below:
String event = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
Pattern p = Pattern.compile("^\|(\w*)\|(\d+)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|\w+\|\w+\|\d{14}\|$");
Matcher mat = p.matcher(event);
StringBuffer aux = new StringBuffer();
mat.appendReplacement(aux, mat.group(5));
String newString = aux.toString();
But the value of newString is 50200, so basically I want to replace it with 12345, so the String would look like this |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Thanks in advance for your help
The thing is I have to use the regex to check the format of the String before doing the replace, because there could be other String with different formats
You can use indexOf to find the second position, then substring around the value you want to replace.
For example
public static void main(String[] args) {
String s = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String find = "50200";
String replace = "12345";
int firstOccur = s.indexOf(find);
int secondOccur = s.indexOf(find, firstOccur+find.length());
StringBuilder sb = new StringBuilder(s.substring(0, secondOccur));
sb.append(replace);
sb.append(s.substring(secondOccur+find.length()));
System.out.println(sb.toString());
// |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
}
Since question has been tagged as regex and non-regex solution is possible but a bit longish here is a simple one line regex solution:
String data = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String srch = "|50200|";
String repl = "|12345|";
String rdata = data.replaceFirst("^(.*?(\\|50200\\|).*?)\\2", "$1|12345|");
//=> |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Regex ^(.*?(\|50200\|).*?)\2 finds 2nd instance of |50200| and captures everything before 2nd instance into captured group #1. We use backreference $1 in replacement to put that captured text back.
RegEx Demo
If I have a key that has the following sequence of characters: _(some number)_1. How can I just return (some number).
For example if the key is _6654_1 I just need value 6654. The problem/issue that's really confusing me is the number could be any length like _9332123425234_1 in which case I would just need the 9332123425234.
Here's what I've tried so far:
Pattern p = Pattern.compile("_[\\d]_1");
Matcher match = p.matcher(request.getParameter("course_id"));
but this won't cover the case where the middle number can be any number (not just four digits) will it?
You could just figure out the indexOf('_') and then use substring. No need for regular expressions.
...but since you asked for regular expressions, here you go:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String str = "_6654_1";
Pattern p = Pattern.compile("_(\\d+)_1");
Matcher m = p.matcher(str);
if (m.matches())
System.out.println(m.group(1)); // prints 6654
}
}
(And here is the substring-approach for comparison:)
String str = "_6654_1";
String num = str.substring(1, str.indexOf('_', 1));
System.out.println(num); // prints 6654
And, a final solution, using a simple split("_"):
String str = "_6654_1";
System.out.println(str.split("_")[1]); // prints.... you guessed it: 6654
Do you really need regexp? You can use substring and indexOf:
String st = "_9332123425234_1";
String number = st.substring(1,st.indexOf('_',1));
Assuming you have the underscores before and after your digit sequence, you could use _(\d+)_ to create a Capturing Group.
See http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
You might also want to consider using a Splitter:
Splitter
This might be more efficient than a regex and since it returns all the elements you will be the before and after elements as well as the number in the middle. So, if you eventually need the number after the second "_" this might be the better way to go.
I have been trying to figure out how to extract a portion of a string between two special characters ' and " I've been looking into regex, but frankly I cannot understand it.
Example in Java code:
String str="21*90'89\"";
I would like to pull out 89
In general I would just like to know how to extract part of a string between two specific characters please.
Also it would be nice to know how to extract part of the string from the beginning to a specific character like to get 21.
Try this regular expression:
'(.*?)"
As a Java string literal you will have to write it as follows:
"'(.*?)\""
Here is a more complete example demonstrating how to use this regular expression with a Matcher:
Pattern pattern = Pattern.compile("'(.*?)\"");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
See it working online: ideone
If you'll always have a string like that (with 3 parts) then this is enough:
String str= "21*90'89\"";
String between = str.split("\"|'")[1];
Another option, if you can assure that your strings will always be in the format you provide, you can use a quick-and-dirty substring/indexOf solution:
str.substring(str.indexOf("'") + 1, str.indexOf("\""));
And to get the second piece of data you asked for:
str.substring(0, str.indexOf("*"));
public static void main(final String[] args) {
final String str = "21*90'89\"";
final Pattern pattern = Pattern.compile("[\\*'\"]");
final String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));
}
Is what you are looking for... The program described above produces:
[21, 90, 89]
I'm missing the simplest possible solution here:
str.replaceFirst(".*'(.*)\".*", "$1");
This solution is by far the shortest, however it has some drawbacks:
In case the string looks different, you get the whole string back without warning.
It's not very efficient, as the used regex gets compiled for each use.
I wouldn't use it except as a quick hack or if I could be really sure about the input format.
String str="abc#defg#lmn!tp?pqr*tsd";
String special="!?##$%^&*()/<>{}[]:;'`~";
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=0;i<str.length();i++)
{
for(int j=0;j<special.length();j++)
if(str.charAt(i)==special.charAt(j))
al.add(i);
}
for(int i=0;i<al.size()-1;i++)
{
int start=al.get(i);
int end=al.get(i+1);
for(int j=start+1;j<end;j++)
System.out.print(str.charAt(j));
System.out.print(" ");
}
String str= 21*90'89;
String part= str.split("[*|']");
System.out.println(part[0] +""+part[1]);
As per my project I need to devide a string into two parts.
below is the example:
String searchFilter = "(first=sam*)(last=joy*)";
Where searchFilter is a string.
I want to split above string to two parts
first=sam* and last=joy*
so that i can again split this variables into first,sam*,last and joy* as per my requirement.
I dont have much hands on experience in java. Can anyone help me to achieve this one. It will be very helpfull.
Thanks in advance
The most flexible way is probably to do it with regular expressions:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
// Create a regular expression pattern
Pattern spec = Pattern.compile("\\((.*?)=(.*?)\\)");
// Get a matcher for the searchFilter
String searchFilter = "(first=sam*)(last=joy*)";
Matcher m = spec.matcher(searchFilter);
// While a "abc=xyz" pattern can be found...
while (m.find())
// ...print "abc" equals "xyz"
System.out.println("\""+m.group(1)+"\" equals \""+m.group(2)+"\"");
}
}
Output:
"first" equals "sam*"
"last" equals "joy*"
Take a look at String.split(..) and String.substring(..), using them you should be able to achieve what you are looking for.
you can do this using split or substring or using StringTokenizer.
I have a small code that will solve ur problem
StringTokenizer st = new StringTokenizer(searchFilter, "(||)||=");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
It will give the result you want.
I think you can do it in a lot of different ways, it depends on you.
Using regexp or what else look at https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html.
Anyway I suggest:
int separatorIndex = searchFilter.indexOf(")(");
String filterFirst = searchFilter.substring(1,separatorIndex);
String filterLast = searchFilter.substring(separatorIndex+1,searchFilter.length-1);
This (untested snippet) could do it:
String[] properties = searchFilter.replaceAll("(", "").split("\)");
for (String property:properties) {
if (!property.equals("")) {
String[] parts = property.split("=");
// some method to store the filter properties
storeKeyValue(parts[0], parts[1]);
}
}
The idea behind: First we get rid of the brackets, replacing the opening brackets and using the closing brackets as a split point for the filter properties. The resulting array includes the String {"first=sam*","last=joy*",""} (the empty String is a guess - can't test it here). Then for each property we split again on "=" to get the key/value pairs.