Extract string between curly braces in java - java

I have String {a,b,c},{1,2,3}. How to extract to get like
String1 = a,b,c;
String2 = 1,2,3;
I have tried someting like this, but that does not work.
String result1 = str.substring(str.indexOf("{") + 1, str.indexOf("},"));
String result2 = str.substring(str.indexOf(",{") + 1, str.indexOf("}"));

There is an indexOf method that takes the index from which to search
String str = "{a,b,c},{1,2,3}";
int startingIndex = str.indexOf("{");
int closingIndex = str.indexOf("}");
String result1 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result1);
startingIndex = str.indexOf("{", closingIndex + 1);
closingIndex = str.indexOf("}", closingIndex + 1);
String result2 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result2);
In the second block, we make the search start at closingIndex + 1 where closingIndex is the index of the last seen }.

You can use a regular expression for that e.g.
Matcher m = Pattern.compile("(?<=\\{).+?(?=\\})").matcher("{a,b,c},{1,2,3}");
while(m.find()){
System.out.println(m.group());
// a,b,c
// 1,2,3
}

One of the possible solutions for this task will be using Pattern class.
It should be a much more elegant solution for getting values between braces.
For matching the first group regex should be: \{([^}]*)\}.
Just add a separator between group , and repeat regex again. Now you can get results separately.
Here is code demo:
public class RegexDemo {
public static void main(String[] args) {
String str = "{a,b,c},{1,2,3}";
Pattern pattern = Pattern.compile("\\{([^}]*)\\},\\{([^}]*)\\}");
Matcher matcher = pattern.matcher(str);
String first = null;
String second = null;
if (matcher.find()) {
first = matcher.group(1);
second = matcher.group(2);
}
System.out.printf("First: %s\nSecond: %s\n", first, second);
}
}
Output:
First: a,b,c
Second: 1,2,3

Related

Java replaceAll ' with '' except first and last occurrence

I want to replace all occurrences of single quotations with two quotations, except in first and last occurrence, I managed to get to exclude the last occurrence using regex as follows
String toReplace = "'123'456'";
String regex = "'(?=.*')";
String replaced = toReplace.replaceAll(regex,"''");
System.out.println(replaced);
Here I get
''123''456'
How do I get
'123''456'
Thank you.
There is a pithy saying about regular expressions and two problems, but I'll skip that and suggest you simplify this by using a StringBuilder; find the index of both the first ' and the last ' in your input, then iterate between those indices looking for ' (and replacing with ''). Something like,
StringBuilder sb = new StringBuilder(toReplace);
int first = toReplace.indexOf("'"), last = toReplace.lastIndexOf("'");
if (first != last) {
for (int i = first + 1; i < last; i++) {
if (sb.charAt(i) == '\'') {
sb.insert(i, '\'');
i++;
}
}
}
toReplace = sb.toString();
int first = toReplace.indexOf("'") + 1;
int last = toReplace.lastIndexOf("'");
String afterReplace = toReplace.substring(0, first)
+ toReplace.substring( first,last ).replaceAll("'", "''")
+ toReplace.substring(last);
System.out.println(afterReplace);
With StringBuilder
String afterReplace = new StringBuilder()
.append(toReplace, 0, first)
.append(toReplace.substring(first, last).replaceAll("'", "''"))
.append(toReplace, last, toReplace.length())
.toString();
Or with String.format
String afterReplace = String.format("%s%s%s",
toReplace.substring(0, first),
toReplace.substring(first, last).replaceAll("'", "''"),
toReplace.substring(last));
Regex expression: (?<=')(. *)(?=')
It will help you to find out your result and then you can replace it.
This can be achieved with regex as well:
// String to be scanned to find the pattern.
String line = "'123'456'";
String pattern = "(?>^')(.*)(?>'$)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(1) );
String replaced = m.group(1).replaceAll("'","\"");
System.out.println("replaced value: " + replaced );
}else {
System.out.println("NO MATCH");
}

How to get String between last two underscore

I have a string "abcde-abc-db-tada_x12.12_999ZZZ_121121.333"
The result I want should be 999ZZZ
I have tried using:
private static String getValue(String myString) {
Pattern p = Pattern.compile("_(\\d+)_1");
Matcher m = p.matcher(myString);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
}
else {
System.out.println("not found");
}
}
If you want to continue with a regex based approach, then use the following pattern:
.*_([^_]+)_.*
This will greedily consume up to and including the second to last underscrore. Then it will consume and capture 9999ZZZ.
Code sample:
String name = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
Pattern p = Pattern.compile(".*_([^_]+)_.*");
Matcher m = p.matcher(name);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
} else {
System.out.println("not found");
}
Demo
Using String.split?
String given = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String [] splitted = given.split("_");
String result = splitted[splitted.length-2];
System.out.println(result);
Apart from split you can use substring as well:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String ss = (s.substring(0,s.lastIndexOf("_"))).substring((s.substring(0,s.lastIndexOf("_"))).lastIndexOf("_")+1);
System.out.println(ss);
OR,
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String arr[] = s.split("_");
System.out.println(arr[arr.length-2]);
The get text between the last two underscore characters, you first need to find the index of the last two underscore characters, which is very easy using lastIndexOf:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String r = null;
int idx1 = s.lastIndexOf('_');
if (idx1 != -1) {
int idx2 = s.lastIndexOf('_', idx1 - 1);
if (idx2 != -1)
r = s.substring(idx2 + 1, idx1);
}
System.out.println(r); // prints: 999ZZZ
This is faster than any solution using regex, including use of split.
As I misunderstood the logic from the code in question a bit with the first read and in the meantime there appeared some great answers with the use of regular expressions, this is my try with the use of some methods contained in String class (it introduces some variables just to make it more clear to read, it could be written in the shorter way of course) :
String s = "abcde-abc-db-ta__dax12.12_999ZZZ_121121.333";
int indexOfLastUnderscore = s.lastIndexOf("_");
int indexOfOneBeforeLastUnderscore = s.lastIndexOf("_", indexOfLastUnderscore - 1);
if(indexOfLastUnderscore != -1 && indexOfOneBeforeLastUnderscore != -1) {
String sub = s.substring(indexOfOneBeforeLastUnderscore + 1, indexOfLastUnderscore);
System.out.println(sub);
}

How to use regex to split a string containing numbers and letters in java

My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123

Java string -> two numbers

The operation I'm hoping to perform is to go from:
String "32.63578..."
to:
float 32.63
long 578... //where '...' is rest of string
Something like the following in Python:
split = str.find('.')+2
float = str[:split]
long = str[split:]
I'm new to Java, so I began by trying to look up equivalents, however it seems like a more convoluted solution than perhaps a regex would be? Unless there's more similar functions to python than splitting into a char array, and repeatedly iterating over?
Use indexOf and substring methods:
String str = "32.63578";
int i = str.indexOf(".") + 3;
String part1 = str.substring(0, i); // "32.63"
String part2 = str.substring(i); // "578"
float num1 = Float.parseFloat(part1); // 32.63
long num2 = Long.parseLong(part2); // 578
Regular expression alternative:
String str = "32.63578";
String[] parts = str.split("(?<=\\.\\d{2})");
System.out.println(parts[0]); // "32.63"
System.out.println(parts[1]); // "578"
About the regular expression used:
(?<=\.\d{2})
It's positive lookbehind (?<=...). It matches at the position where is preceded by . and 2 digits.
You can use the split method in String if you want to cleanly break the two parts.
However, if you want to have trailing decimals like in your example, you'll probably want to do something like this:
String str = "32.63578...";
String substr1, substr2;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '.')
{
substr1 = str.substring(0, i + 3);
substr2 = str.substring(i + 3, str.length());
break;
}
}
//convert substr1 and substr2 here
String s ="32.63578";
Pattern pattern = Pattern.compile("(?<Start>\\d{1,10}.\\d{1,2})(?<End>\\d{1,10})");
Matcher match = pattern.matcher(s);
if (match.find()) {
String start = match.group("Start");
String ending = match.group("End");
System.out.println(start);
System.out.println(ending);
}

How to get with JAVA a specific value for one substring from string?

I have ONE string field which is in format:
"TransactionID=30000001197169 ExecutionStatus=6
additionalCurrency=KMK
pin= 0000"
So they are not separated with some ; оr , they are not seperated even with one blank space.
I want to get value for Execution Status and put it in some field?
How to achieve this?
Thanks for help
This works. But I am not sure this is the most optimal.It just solves your problem.
String s = "TransactionID=30000001197169ExecutionStatus=6additionalCurrency=KMKpin=0000";
if(s!=null && s.contains("ExecutionStatus="))
{
String s1[] = s.split("ExecutionStatus=");
if(s1!=null && s1.length>1)
{
String line = s1[1];
String pattern = "[0-9]+";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Match");
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
}
}
In your example they are indeed seperated by blanks, but the following should be working without blanks, too. Assuming your String is stored in String arguments
String executionStatus;
String[] anArray = arguments.split("=");
for (int i; i < anArray.length; i++)
if (anArray[i].contains("ExecutionStatus")){
executionStatus = anArray[++i].replace("additionalCurrency","");
executionStatus = executionStatus.trim();
}
}
Check if it contains() ExecutionStatus=
If yes then split the string with ExecutionStatus=
Now take the Second string from array find the first occurance of non digit char and use substring()
Assuming all that white space is present in your string, this works.
String str = "\"TransactionID=30000001197169 ExecutionStatus=6\n" +
" additionalCurrency=\"KMK\"\n" +
" pin= \"0000\"\"";
int start = str.indexOf("ExecutionStatus=") + "ExecutionStatus=".length();
int status = 0;
if (start >= 0) {
String strStatus = str.substring(start, str.indexOf("additionalCurrency=") - 1);
try {
status = Integer.parseInt(strStatus.trim());
} catch (NumberFormatException e) {
}
}
At the risk of attracting "... and now you have two problems!" comments, this is probably easiest done with regexes (str is the String defined above):
Pattern p = Pattern.compile("ExecutionStatus\\s*=\\s*(\\d+)"); // Whitespace matching around equals for safety, capturing group around the digits of the status)
Matcher m = p.matcher(str);
String status = m.find() ? m.group(1) : null;

Categories