I have a String "abcabc" and I want to split it and print like this:
abc
abc
Code definition for string:
String word = "abcabc";
We can try using String#replaceAll for a one line option:
String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);
This prints:
abc
abc
The idea is to apply a pattern to the entire string which matches and captures some quantity, which is then followed by the same quantity to the end. Here is the pattern explained as executed against your exact input abcabc:
(.*) match 'abc'
(?=\1$) then lookahead and assert that what follows to the end of the string
is exactly another 'abc'
.* consume, but do not match, the remainder of the input (which must be 'abc')
Then, we replace with $1\n$1, which is the first capture group twice, separated by a newline.
The string split():
public class Split {
public static void main(String args[])
{
String str = "ABC#ABC";
String[] arrOfStr = str.split("#", 5);
for (String a : arrOfStr)
System.out.println(a);
}
}
This Also Prints :
ABC
ABC
class Stack{
public static void main(String $[]){
foo();
}
public static void foo(){
String in="abc abc abc";//spaces are used as seperator.
String res[]=in.split(" ");//Returns an Array of String
for(int i=0;i<res.length;i++)
System.out.println(res[i]);
}
}
output:
abc
abc
abc
Related
I have a String to be checked for regex :
"field":"Testing, for something \"and something\""
which I want to pattern match and replace with :
"field":"SAFE"
For this, I am trying to pattern match and capture till the last inverted commas. I have tried the following regex, but its not matching :
Pattern p = Pattern.compile("\"field\":\".*?(?!\\\")\"");
New to regex, can anyone suggest what I might be doing wrong? Thanks!
EDIT :
I guess the question was not clear. Apologies. The above is not the end of the string. It can contain more fields in succession :
"field":"Testing, for something \"and something\"", "new_field":"blahblah", ...
output should be :
"field":"SAFE", "new_field":"blahblah", ...
You can do it as follows:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\"";
str = str.replaceAll("(\"field\":).*", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE"
Explanation:
(\"field\":) is the first capturing group
.* specifies all characters
$1 specifies the first capturing group
Update:
Writing this update based on the clarification from OP.
You can use positive lookahead for comma as shown below:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\", \"new_field\":\"blahblah\"";
str = str.replaceAll("(\"field\":).*(?=,)", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE", "new_field":"blahblah"
Here is an example.
$str = '"field":"Testing, for something \"and something\""';
echo preg_replace('/(\"field\":\")(.*)(\")/i', "$1SAFE$3", $str);
Regex is tested: here.
Given this text:
$F{abc} and $F{def}
I need to get
abc and def
For that, I would use this regex to find the values \$F\{\w*\} but I need to get what's represented by w*:
str.replaceAll("\\$F\{\\w*\\}", "??" );
Is this doable with a Java function or I need to write the routine?
You can capture the text in a group:
str = str.replaceAll("\\$F\\{(\\w*)}", "$1");
Update
I didn't read your question completely. Thanks to The fourth bird for pointing it out. Given below is the code for the expected output, abc and def
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("\\$F\\{(\\w*)\\}", "$1"));
}
}
Output:
abc and def
All you need to do is to replace the given string with the capturing group(1). The explanation in the original answer is still valid for this update.
Original answer:
You can use the regex, (\$F\{)(\w*)(\}) and replace the capturing group(2) with ?? and preserve the capturing group(1) and the capturing group(3) as shown below:
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("(\\$F\\{)(\\w*)(\\})", "$1??$3"));
}
}
Output:
$F{??} and $F{??}
Check this for an illustration of all the capturing groups in the regex, (\$F\{)(\w*)(\}).
One way is to use the regex (\\$F\\{)|(\\}) you can both remove the "$F{" and "}" parts using replaceAll():
String str = "$F{abc} and $F{def}";
str = str.replaceAll("(\\$F\\{)|(\\})", "");
About regex:
(\\$F\\{) : 1. group "$F{"
| : OR
(\\}) : 2. group "}"
Other way is to use a capture group reference in the replacement parameter. $1 stands for the capture group (\\w*) that corresponds to abc and def
String str = "$F{abc} and $F{def}";
str = str.replaceAll("\\$F\\{(\\w*)\\}", "$1" );
System.out.println(str);
Output:
abc and def
I have tried to split a string using split method, but I'm facing some problem in using split method.
String str="1-DRYBEANS,2-PLAINRICE,3-COLDCEREAL,4-HOTCEREAL,51-ASSORTEDETHNIC,GOURMET&SPECIALTY";
List<String> zoneArray = new ArrayList<>(Arrays.asList(zoneDescTemp.split(",")));
Actual output :
zoneArray = {"1-DRYBEANS","2-PLAINRICE","3-COLDCEREAL","4-HOTCEREAL","51-ASSORTEDETHNIC","GOURMET&SPECIALTY"}
Expected output :
zoneArray = {"1-DRYBEANS","2-PLAINRICE","3-COLDCEREAL","4-HOTCEREAL","51-ASSORTEDETHNIC,GOURMET&SPECIALTY"}
Any help would be appreciated.
Use split(",(?=[0-9])")
You are not just splitting by comma, but splitting by comma only if it is followed by a digit from 0-9. This is also known as positive lookahead (?=).
Take a look at this code snippet for example:
public static void main(String[] args) {
String str="1-DRYBEANS,2-PLAINRICE,3-COLDCEREAL,4-HOTCEREAL,51-ASSORTEDETHNIC,GOURMET&SPECIALTY";
String[] array1= str.split(",(?=[0-9])");
for (String temp: array1){
System.out.println(temp);
}
}
}
Use a look-ahead within your regex, one that uses comma (not in the look-ahead), followed by a number (in the look-head). \\d+ will suffice for number. The regex can look like:
String regex = ",(?=\\d+)";
For example:
public class Foo {
public static void main(String[] args) {
String str = "1-DRYBEANS,2-PLAINRICE,3-COLDCEREAL,4-HOTCEREAL,51-ASSORTEDETHNIC,GOURMET&SPECIALTY";
String regex = ",(?=\\d+)";
String[] tokens = str.split(regex);
for (String item : tokens) {
System.out.println(item);
}
}
}
what this does is split on a comma that is followed by numbers, but does not remove from the output, the numbers since they are part of the look-ahead.
For more on look-ahead, look-behind and look-around, please check out this relevant tutorial page.
This is my program
package com.util;
public class SplitBy {
public static void main(String args[]) {
String name = "Masala Roasted with peanuts(49)";
String category_id = "";
if (!name.contains(",")) {
if (name.contains("(")) {
String[] parts = name.split("\\(");
category_id = parts[1];
System.out.println(category_id);
}
}
}
}
With this the current output is
49)
Please let me know how to get rmove the closing bracket and produce only
49
You can split the String on both brackets:
String[] parts = name.split("[()]");
[()] is a regular expression matching both the openning and closing brackets. As split() is splitting the String around matches, the closing bracket will not be included in the resulting value.
According to the split() javadoc,
Trailing empty strings are therefore not included in the resulting array.
which means that it won't add an empty element at the end of your array.
You can do something like this:
category_id = category_id.substring(0, category_id.length() - 1);
Which will remove the last character from your String.
You can look for both parentheses and only print the content in between:
category_id = name.substring(name.indexOf("(")+1, name.indexOf(")"));
Check this out
package com.util;
public class SplitBy {
public static void main(String args[]) {
String s = "";
Pattern pattern = Pattern.compile("(?<=)(\\d+)");
String EXAMPLE_TEST = "Masala Roasted with peanuts(49)";
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
while (matcher.find()) {
s = matcher.group(1);
}
System.out.println(s);
}
}
Example
input: abc def abc abc pqr
I want to to replace abc at third position with xyz.
output: abc gef abc xyz pqr
Thanks in advance
One way to do this would be to use.
String[] mySplitStrings = null;
String.Split(" ");
mySplitString[3] = "xyz";
And then rejoin the string, its not the best way to do it but it works, you could put the whole process into a function like.
string ReplaceStringInstance(Seperator, Replacement)
{
// Do Stuff
}
Group the three segments, that are the part before the replaced string, the replaced string and the rest and assemble the prefix, the replacement and the suffix:
String pattern = String.format("^(.*?%1$s.*?%1$s.*?)(%1$s)(.*)$", "abc");
String result = input.replaceAll(pattern, "$1xyz$3");
This solution assumes that the whole input is one line. If you have multiline input you'll have to replace the dots as they don't match line separators.
There's plenty of ways to do this, but here's one. It assumes that the groups of letters will be separated by spaces, and looks for the 3rd 'abc' block. It then does a single replace to replace that with 'xyz'.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class main {
private static String INPUT = "abc def abc abc pqr";
private static String REGEX = "((?:abc\\ ).*?(?:abc\\ ).*?)(abc\\ )";
private static String REPLACE = "$1xyz ";
public static void main(String[] args) {
System.out.println("Input: " + INPUT);
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
INPUT = m.replaceFirst(REPLACE);
System.out.println("Output: " + INPUT);
}
}