How to extract a specific substring in Java - java

I have a string that I define as
String string = "<html><color=black><b><center>Line1</center><center>Line2</center></b></font></html>";
that I apply to a JButton to get 2 lines of text on it, and that works perfectly. When I call the JButton.getText() method, it returns the whole string. What I want is to take the string it returns, and get the string "Line1Line2" from it. (So I want to remove all the HTML code and just get the text that appears on the screen.) I have tried using something like
if(string.contains("<html>"))
{
string.replace("<html>", "");
}
and then doing the same thing for all the other "<(stuff)>", but if I then print the string, I still get the whole thing. I think using regular expressions is a better way than to manually remove all the "<(stuff)>", but I don't know how.
Any help would be most appreciated!

string.replace() doesn't modify the string: a String is immutable. It returns a new string where the replacement has been done.
So your code should be
if (string.contains("<html>")) {
string = string.replace("<html>", "");
}

String is immutable, so String#replace does not change the String but rather returns the changed String.
string = string.replace("<html>", "");
and so on should do the thing.

String also has a replaceAll() method.
you could try string.replaceAll("<.*?>", "");
Also keep in mind that Strings in java are immutable and this operation will return a new String with your result

Related

Replace part of string with known beginning and end

I get some string from server with known and unknow parts. For example:
<simp>example1</simp><op>example2</op><val>example2</val>
I do not wish to parse XML or any use of parsing. What I wish to do is replace
<op>example2</op>
with empty string ("") which string will look like:
<simp>example1</simp><val>example2</val>
What I know it start with op (in <>) and ends with /op (in <>) but the content (example2) may vary.
Can you give me pointer how accomplish this?
You can use regex. Something like
<op>[A-Za-z0-9]*<\/op>
should match. But you can adapt it so that it fits your requirements better. For example if you know that only certain characters can be shown, you can change it.
Afterwards you can use the String#replaceAll method to remove all matching occurrences with the empty string.
Take a look here to test the regex: https://regex101.com/r/WhPIv4/3
and here to check the replaceAll method that takes the regex and the replacement as a parameter: https://developer.android.com/reference/java/lang/String#replaceall
You can try
str.replace(str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5),"");
To remove all, use replaceAll()
str.replaceAll(str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5),"");
I tried sample,
String str="<simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val>";
Log.d("testit", str.replaceAll(str.substring(str.indexOf("<op>"), str.indexOf("</op>") + 5), ""));
And the log output was
D/testit: <simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val>
Edit
As #Elsafar said , str.replaceAll("<op>.*?</op>", "") will work.
Use like this:
String str = "<simp>example1</simp><op>example2</op><val>example2</val>";
String garbage = str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5).trim();
String newString = str.replace(garbage,"");
I combined all the answers and eventually used:
st.replaceAll("<op>.*?<\\/op>","");
Thank you all for the help

String replace not working, even after assigning to another variable

Java String.replace not working even after assigning to a variable.
I have a JSON formatted string like as follows.
{"Obligations":["\nAggregate","\nDelay"],"Result":"Permit"}
I want to remove the \n from the string.
I used the following piece of code. There is no difference.
String test =jsonObject.toString().replace("\n", "");
System.err.println(test);
But I get the same result. Is there something wrong in it ?
"\n" means a new line. You must use an escape.
Try it:
String test =jsonObject.toString().replace("\\n", "");
This works.
String test =jsonObject.toString().replace("\\n", "");
System.err.println(test);

Can I add a char to a variable specified position within a string?

OK, this is the line I am working on:
newstring.charAt(w) += p;
trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?
Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.
If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.
Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.
Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -
str = str.substring(0, w) + "p" + str.substring(w);
But, of course, using StringBuilder as specified in #biziclop's answer is the best approach you can follow.

How Do Insert a char in string (java/groovy)?

I have a string like :
string = abcdefghabcd
Now lets say I want to replace the first occurrence of a. I tried something like this :
string[string.indexOf('a')] = '0'
But this doesn't seems to be working. Any other way I can do this?
Thanks in advance.
In Java you can use String.replaceFirst() :
String s = "abcdefghabcd";
s = s.replaceFirst("a", "0");
System.out.println(s);
Output will be :
0bcdefghabcd
Warning : the replaceFirst() method takes a regex : so if you want to replace a special character like [ you need to escape by putting a \ before it. \ being a special character itself, you need to double it as follow :
s = s.replaceFirst("\\[", "0");
Here is the documentation on Java Regular Expressions. Also, here is Oracle's Java tutorial on manipulating Characters in Strings.
You should be aware that strings in Java are immutable. They cannot be changed. Any method you use to "change" a string will have to return a new string. If you want to modify a string directly you will need to use a mutable string type like StringBuilder.
There are many methods in the String API docs that will help you get a modified version of your string, including s.replace(), s.replaceAll(),s.replaceFirst(), ... or you could use a combination of substring and "+" to create a new string.
If you really want to treat the string as an array as in your initial example, you could use String.getChars to get an array of characters, manipulate that, and then use the String constructor String(char[]) to convert back to a String object.
In this program you will need use replaceFirst() method of String class in Java.
/*
Java String replace example.
This Java String Replace example describes how replace method of java String
class can be used to replace character or substring by new one.
*/
public class JavaStringReplaceExample{
public static void main(String args[])
{
String str="abcdefghabcd";
System.out.println(str.replaceFirst("a", "0"));
}
}
you can refer to here for details

XML String replacement

How can I replace String in xml ..
I've
<schema>src/main/castor/document.xsd</schema>
I need to replace to
<schema>cs/src/main/castor/document.xsd</schema>
If I use simple , xmlInStr is the string form of xml document
xmlInStr.replaceAll(
"src/main/castor/GridDocument.xsd",
"correspondenceCastor/src/main/castor/GridDocument.xsd"
);
I Tried replace instead ,
xmlInStr.replace("src/main/castor/GridDocument.xsd".toCharArray().toString(), "correspondenceCastor/src/main/castor/GridDocument.xsd".toCharArray().toString());
it's not working . any clues
Managed like this
int indx = from.indexOf(from);
xmlInStr = xmlInStr.substring(0,indx) + to + xmlInStr.substring(indx + from.length());
String.replaceAll takes a regular expression as the first argument. Use replace instead.
You use an XML parser to parse and manipulate XML, don't try and use regular expression based string replacement mechanisms it will not work and will only bring pain and suffering.
You can use repalce or replaceAll. Anyway you have to use the value returned by this method. The method does not modify the string itself because String class is immutable.
Both replace() and replaceAll() don't actually replace anything in the string (strings are immutable). They return a new string instead, but you just discard the return value, that's why you don't see it anywhere. By the way, that .toCharArray().toString() looks completely useless to me. A character literal is already a full-fledged String.
But you really should use an XML parser instead. Unless your task is very simple and you're absolutely sure that you don't replace anything that shouldn't be replaced.

Categories