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]);
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 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));
}
}
}
I am trying to break apart a very simple collection of strings that come in the forms of
0|0
10|15
30|55
etc etc. Essentially numbers that are seperated by pipes.
When I use java's string split function with .split("|"). I get somewhat unpredictable results. white space in the first slot, sometimes the number itself isn't where I thought it should be.
Can anybody please help and give me advice on how I can use a reg exp to keep ONLY the integers?
I was asked to give the code trying to do the actual split. So allow me to do that in hopes to clarify further my problem :)
String temp = "0|0";
String splitString = temp.split("|");
results
\n
0
|
0
I am trying to get
0
0
only. Forever grateful for any help ahead of time :)
I still suggest to use split(), it skips null tokens by default. you want to get rid of non numeric characters in the string and only keep pipes and numbers, then you can easily use split() to get what you want. or you can pass multiple delimiters to split (in form of regex) and this should work:
String[] splited = yourString.split("[\\|\\s]+");
and the regex:
import java.util.regex.*;
Pattern pattern = Pattern.compile("\\d+(?=([\\|\\s\\r\\n]))");
Matcher matcher = pattern.matcher(yourString);
while (matcher.find()) {
System.out.println(matcher.group());
}
The pipe symbol is special in a regexp (it marks alternatives), you need to escape it. Depending on the java version you are using this could well explain your unpredictable results.
class t {
public static void main(String[]_)
{
String temp = "0|0";
String[] splitString = temp.split("\\|");
for (int i=0; i<splitString.length; i++)
System.out.println("splitString["+i+"] is " + splitString[i]);
}
}
outputs
splitString[0] is 0
splitString[1] is 0
Note that one backslash is the regexp escape character, but because a backslash is also the escape character in java source you need two of them to push the backslash into the regexp.
You can do replace white space for pipes and split it.
String test = "0|0 10|15 30|55";
test = test.replace(" ", "|");
String[] result = test.split("|");
Hope this helps for you..
You can use StringTokenizer.
String test = "0|0";
StringTokenizer st = new StringTokenizer(test);
int firstNumber = Integer.parseInt(st.nextToken()); //will parse out the first number
int secondNumber = Integer.parseInt(st.nextToken()); //will parse out the second number
Of course you can always nest this inside of a while loop if you have multiple strings.
Also, you need to import java.util.* for this to work.
The pipe ('|') is a special character in regular expressions. It needs to be "escaped" with a '\' character if you want to use it as a regular character, unfortunately '\' is a special character in Java so you need to do a kind of double escape maneuver e.g.
String temp = "0|0";
String[] splitStrings = temp.split("\\|");
The Guava library has a nice class Splitter which is a much more convenient alternative to String.split(). The advantages are that you can choose to split the string on specific characters (like '|'), or on specific strings, or with regexps, and you can choose what to do with the resulting parts (trim them, throw ayway empty parts etc.).
For example you can call
Iterable<String> parts = Spliter.on('|').trimResults().omitEmptyStrings().split("0|0")
This should work for you:
([0-9]+)
Considering a scenario where in we have read a line from csv or xls file in the form of string and need to separate the columns in array of string depending on delimiters.
Below is the code snippet to achieve this problem..
{ ...
....
String line = new BufferedReader(new FileReader("your file"));
String[] splittedString = StringSplitToArray(stringLine,"\"");
...
....
}
public static String[] StringSplitToArray(String stringToSplit, String delimiter)
{
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
char[] chars = stringToSplit.toCharArray();
for (int i=0; i 0) {
tokens.addElement(token.toString());
token.setLength(0);
i++;
}
} else {
token.append(chars[i]);
}
}
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] preparedArray = new String[tokens.size()];
for (int i=0; i < preparedArray.length; i++) {
preparedArray[i] = (String)tokens.elementAt(i);
}
return preparedArray;
}
Above code snippet contains method call to StringSplitToArray where in the method converts the stringline into string array splitting the line depending on the delimiter specified or passed to the method. Delimiter can be comma separator(,) or double code(").
For more on this, follow this link : http://scrapillars.blogspot.in
I am having a group of strings in Arraylist.
I want to remove all the strings with only numbers
and also strings like this : (0.75%),$1.5 ..basically everything that does not contain the characters.
2) I want to remove all special characters in the string before i write to the console.
"God should be printed God.
"Including should be printed: quoteIncluding
'find should be find
Java boasts a very nice Pattern class that makes use of regular expressions. You should definitely read up on that. A good reference guide is here.
I was going to post a coding solution for you, but styfle beat me to it! The only thing I was going to do different here was within the for loop, I would have used the Pattern and Matcher class, as such:
for(int i = 0; i < myArray.size(); i++){
Pattern p = Pattern.compile("[a-z][A-Z]");
Matcher m = p.matcher(myArray.get(i));
boolean match = m.matches();
//more code to get the string you want
}
But that too bulky. styfle's solution is succinct and easy.
When you say "characters," I'm assuming you mean only "a through z" and "A through Z." You probably want to use Regular Expressions (Regex) as D1e mentioned in a comment. Here is an example using the replaceAll method.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(5);
list.add("\"God");
list.add(""Including");
list.add("'find");
list.add("24No3Numbers97");
list.add("w0or5*d;");
for (String s : list) {
s = s.replaceAll("[^a-zA-Z]",""); //use whatever regex you wish
System.out.println(s);
}
}
}
The output of this code is as follows:
God
quotIncluding
find
NoNumbers
word
The replaceAll method uses a regex pattern and replaces all the matches with the second parameter (in this case, the empty string).
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.