Split and extract java string multiple times - java

I have a string in java e.g:
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)"
The string contains variables for which i need to extract information out of. What i am looking for end result is something like this:
String myVar = "(some data[some text])"
String someVar = "(table spoon fork(chairs cloths)[cups]"
String anotherVar = "(balloons{clowns} bubbles)"
The string may also be like:
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups]"
And result should be:
String myVar = "(some data[some text])"
String someVar = "(table spoon fork(chairs cloths)[cups]"
String anotherVar = ""
I have tried:
String[] parts = string.split("MYVAR1");
But that gets me everything and not just the MYVAR1 contents.

try this
public class TestClass {
public static void main(String a[]){
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)";
System.out.println("myVar = " + getValue(myString, "MYVAR1", "SOMEVAR"));
System.out.println("someVar = " + getValue(myString, "SOMEVAR", "ANOTHERVAR"));
System.out.println("anotherVar = "+ getValue(myString, "ANOTHERVAR", null));
System.out.println();
myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups]";
System.out.println("myVar = " + getValue(myString, "MYVAR1", "SOMEVAR"));
System.out.println("someVar = " + getValue(myString, "SOMEVAR", "ANOTHERVAR"));
System.out.println("anotherVar = " + getValue(myString, "ANOTHERVAR", null));
}
private static String getValue(String myString, String name,String nextName){
if(myString == null || name == null) return "";
int a = myString.indexOf(name);
if (a == -1) return "";
if(nextName == null){
return myString.substring(a+name.length());
}
else {
int b = myString.indexOf(nextName);
if(b>-1){
return myString.substring(a + name.length(), b);
}
else {
return myString.substring(a + name.length());
}
}
}
}

Try below code :
String myString = "MYVAR1(some data[some text]) SOMEVAR(table spoon fork(chairs cloths)[cups] ANOTHERVAR(balloons{clowns} bubbles)";
String myVar1 = myString.split("MYVAR1")[1].split("SOMEVAR")[0];
String tmpSomeVAR = myString.split("SOMEVAR")[1];
String someVar = "";
String ANOTHERVAR = "";
String[] tmp = tmpSomeVAR.split("ANOTHERVAR");
if (tmpSomeVAR.split("ANOTHERVAR").length == 1) {
someVar = tmpSomeVAR;
} else {
String[] parts = tmpSomeVAR.split("ANOTHERVAR");
someVar = parts[0];
ANOTHERVAR = parts[1];
}
System.out.println(myVar1);
System.out.println(someVar);
System.out.println(ANOTHERVAR);

From what I understood, your trying to extract words within brackets.
You can use regular expression to match what you need.
For example:
String regex = “\\(.+\\)(\\[.+\\]){0,1}” // this match everything inside the brackets and match what’s inside [] when present

Related

How to split string based on length and space using Java

I'm having a string as following in Java. The length of the string is not known and as an example it will be something like below.
String str = "I love programming. I'm currently working with Java and C++."
For some requirement I want to get first 15 characters. Then 30, 45, 70 next characters. Once the string was split if the name was not meaningful then it should be split from nearest space. For the above example output is as following.
String strSpli1 = "I love "; //Since 'programming' is splitting it was sent to next split
String strSpli2 = "programming. I'm currently ";//Since 'working' is splitting it was sent to next split
String strSpli3 = "working with Java and C++.";
Please help me to achieve this.
Updated answer for anybody having this kind of requirement.
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
try {
strSpli1 = str.substring(15);
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
strSpli1 = str.substring(0, pos);
str = str.substring(pos);
try {
strSpli2 = str.substring(45);
int pos1 = str.lastIndexOf(" ", 46);
if (pos1 == -1) {
pos1 = 45;
}
strSpli2 = str.substring(0, pos1);
str = str.substring(pos1);
try {
strSpli3 = str.substring(70);
int pos2 = str.lastIndexOf(" ", 71);
if (pos2 == -1) {
pos2 = 45;
}
strSpli3 = str.substring(0, pos2);
str = str.substring(pos2);
} catch (Exception ex) {
strSpli3 = str;
}
} catch (Exception ex) {
strSpli2 = str;
}
} catch (Exception ex) {
strSpli1 = str;
}
Thank you
use the 2 parameter version of lastIndexOf() to search for space backwards starting from a given position. Example for the first 15 characters:
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
String found = str.substring(0, pos);
str = str.substring(pos+1);
this is missing checks like ensuring the string starts with at least 15 characters, or that pos+1 is valid for given length
suggest having a look at java.text.BreakIterator
why you use so many try catch ? just try this.
public class MyClass {
public static void main(String args[]) {
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
strSpli1 = str.substring(0, 7);
strSpli2 = str.substring(7, 33);
strSpli3 = str.substring(34, str.length());
System.out.println(strSpli1+"\n");
System.out.println(strSpli2+"\n");
System.out.println(strSpli3+"\n");
}
use substring(start index, end index).

How to replace special Character with a String replacer

I have the following Code:
#Test
public void testReplace(){
int asciiVal = 233;
String str = new Character((char) asciiVal).toString();
String oldName = "Fr" + str + "d" + str + "ric";
System.out.println(oldName);
String newName = oldName.replace("é", "_");
System.out.println(newName);
Assert.assertNotEquals(oldName, newName); // Its still equal. Howto Replace with a String
String notTheWayILike = oldName.replace((char) 233 + "", "_"); // I don't want to do this.
Assert.assertNotEquals(oldName, notTheWayILike);
}
How can I replace the character with a String ?
I need this, because they should be userfriendly defined as Strings or chars.

Line Breaks are not being removed with Replace or ReplaceAll Functions

I am getting following values in my String variable:
យោងតាមឯកឧត្តមតាំង សាមឿនលេខាសម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុនសែនបានប្រាប់ក្រុមអ្នក\r\nសារព័ត៌មានថា៖ក្នុងជំនួបសម្តែងការគួរសមនិងទទួលថវិការ៦រយដុល្លាអាមេរិក និងសម្ភារៈឧបករណ៍\r\nព្រមទាំងបរិក្ខារពេទ្យ មួយចំនួនពីក្រុមយុវជនកម្ពុជាជូនលោកជំទាវ អាន្នីសុខអានអនុប្រធានតំណាង\r\nដ៏ខ្ពង់ខ្ពស់សម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុន សែនប្រធានកាកបាទក្រហមកម្ពុជានៅទីស្នាក់ការកណ្តាល\r\nកាកបាទក្រហមកម្ពុជាអូរបែកក្អមក្នុងរាជធានីភ្នំពេញនាថ្ងៃទី២ខែកញ្ញាឆ្នាំ២០១៤។\r\n\r\nលោកជំទាវអាន្នីសុខ អានបានកោតសសើរចំពោះក្រុមយុវជនកម្ពុជាដែលបានយកថវិកានិងសម្ភារៈមកជូន\r\nកាកបាទក្រហមកម្ពុជាសកម្មភាពនេះបង្ហាញពីអោយឃើញពីបេះដូងមនុស្សធម៌នៃវប្បធម៌ចែ
in which i have \r\n with different sequence
for example:
\r\n
\r\n\r\n
\r\n\r\n\r\n\r\n
i have used following all functions none of them works, any one guide me what mistake am i doing?
private List<ContentValues> parseJsonBreakingNews(String json) throws JSONException {
List<ContentValues> result = new ArrayList<ContentValues>();
JSONArray allItems = new JSONArray(json);
JSONObject item;
for (int i = 0; i < allItems.length(); i++) {
item = allItems.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(TableBreakingNews._ID, item.getInt("id"));
String x = item.getString("title_kh");
String y = item.getString("content_kh");
String title = RemoveSpecialCharacters(x);
String description = RemoveSpecialCharacters(y);
values.put(TableBreakingNews.TITLE_KH, title);
values.put(TableBreakingNews.CONTENT_KH,description);
values.put(TableBreakingNews.DATE, item.getString("dt"));
result.add(values);
}
return result;
}
private String RemoveSpecialCharacters(String JunkData)
{
JunkData = JunkData.replaceAll("\\r", "");
JunkData = JunkData.replaceAll("\\n", "");
//JunkData = JunkData.replaceAll("[\n\r]+", " ");
//JunkData = JunkData.replaceAll("[\r\n]+", " ");
//JunkData = JunkData.replaceAll("\\r", "2222222222222");
//JunkData = JunkData.replaceAll("\\n", "111111111111");
//JunkData = JunkData.replaceAll("\\r\\n", "0000000000000000");
// String newLine = System.getProperty("line.separator");
//JunkData = JunkData.replace(newLine, "");
//JunkData = JunkData.replace('\n', '');
//JunkData = RemoveLineTerminationCharacters(JunkData);
//JunkData = RemoveLineTabs(JunkData);
return JunkData;
}
any help would be appreciated.
I can't see the whole code, but i think your problem is the reference from this String, have a look at my test:
Maybe you are calling your method but not updating your real reference of the object.
I don't know exactly what is your problem. if you could, please explain better what you want.
--- Edited ----
Try your method this way:
private String removeSpecialCharacters(String junkData) {
junkData = junkData.replaceAll("(\r\n|\n)", "");
return junkData;
}
Try
replace("\n", "");
or
private static final String newLine = System.getProperty("line.separator");
replace(newline, "");
Something like that should work for you

Words inside square brackes - RegExp

String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N

Java special characters RegEx

I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}

Categories

Resources