Problem replacing a String in Java - java

I am trying to replace a URL with a shortened URL inside of a String:
public void shortenMessage()
{
String body = composeEditText.getText().toString();
String shortenedBody = new String();
String [] tokens = body.split("\\s");
// Attempt to convert each item into an URL.
for( String token : tokens )
{
try
{
Url url = as("mycompany", "someapikey").call(shorten(token));
Log.d("SHORTENED", token + " was shortened!");
shortenedBody = body.replace(token, url.getShortUrl());
}
catch(BitlyException e)
{
//Log.d("BitlyException", token + " could not be shortened!");
}
}
composeEditText.setText(shortenedBody);
// url.getShortUrl() -> http://bit.ly/fB05
}
After the links are shortened, I want to print the modified string in an EditText. My EditText is not displaying my messages properly.
For example:
"I like www.google.com" should be "I like [some shortened url]" after my code executes.

In Java, strings are immutable. String.replace() returns a new string which is the result of the replacement. Thus, when you do shortenedBody = body.replace(token, url.getShortUrl()); in a loop, shortenedBody will hold the result of (only the very) last replace.
Here's a fix, using StringBuilder.
public void shortenMessage()
{
String body = composeEditText.getText().toString();
StringBuilder shortenedBody = new StringBuilder();
String [] tokens = body.split("\\s");
// Attempt to convert each item into an URL.
for( String token : tokens )
{
try
{
Url url = as("mycompany", "someapikey").call(shorten(token));
Log.d("SHORTENED", token + " was shortened!");
shortenedBody.append(url.getShortUrl()).append(" ");
}
catch(BitlyException e)
{
//Log.d("BitlyException", token + " could not be shortened!");
}
}
composeEditText.setText(shortenedBody.toString());
// url.getShortUrl() -> http://bit.ly/fB05
}

You'll probably want String.replaceAll and Pattern.quote to "quote" your string before you pass it to replaceAll, which expects a regex.

Related

Is there a clean way to check if a String contains a char from an other String

I'm currently trying to catch special chars from an URL to change them to their hex value (for example : "This shop" should transform into "This%20shop").
I was wondering if there was some clean was of looking into the string to find each special chars and replace them to their ascii values.
I try to do it because I have to pass PHP arguments into the url using GET.
Here would be an example of an url :
www.mysite.com/page?adress=I am Living here!
My code actually reaplace '%' and ' ' from URLs, but I'd like to change any special chars I've defined.
This is what I've done so far :
private final String specialChars = "!#\\[]`#$%&'()*+-<>=?";
public URL getURL(){
String tempUrl = baseURL;
Set<String> keys = this.arguments.keySet();
for (Map.Entry<String, String> entry : arguments.entrySet()) {
String value = entry.getValue();
if(entry.getValue().contains(specialChars)){
Log.e("INFO", "THIS URL CONTAINS SPECIAL CHARS");
}
//Replacing % char
if(entry.getValue().contains("%")){
Log.i("URL BUILD INFO", "URL ARGS CONTAINS '%'");
value = entry.getValue().replace("%", "%25");
}
//Replacing spaces
if(entry.getValue().contains(" ")){
Log.i("URL BUILD INFO", "URL ARGS CONTAINS SPACE");
value = entry.getValue().replace(" ", "%20");
}
baseURL += entry.getKey() + "=" + value + "&";
}
try{
this.url = new URL(baseURL);
} catch(MalformedURLException e){
Log.e("URL MALFORMED", "YOUR IS MALFORMED");
e.printStackTrace();
}
Log.d("URL IS VALID", url.toString());
return url;
}
From what I understood from String documentation, matches method should only return true if my URL matches exactly my specialChars charSequence, which isn't what I want. But I can't find any other method to do what I'm trying to achieve on the String documentation.
If you're just trying to handle url encoding there are existing solutions for that - see URLEncoder and URLDecoder (good previous answer here)

Splitting the string in java is giving different results than expected [duplicate]

This question already has answers here:
Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) [duplicate]
(1 answer)
Tokenizing a String but ignoring delimiters within quotes
(14 answers)
Closed 6 years ago.
Hi I am new to Java and trying to use the split method provided by java.
The input is a String in the following format
broadcast message "Shubham Agiwal"
The desired output requirement is to get an array with the following elements
["broadcast","message","Shubham Agiwal"]
My code is as follows
String str="broadcast message \"Shubham Agiwal\"";
for(int i=0;i<str.split(" ").length;i++){
System.out.println(str.split(" ")[i]);
}
The output I obtained from the above code is
["broadcast","message","\"Shubham","Agiwal\""]
Can somebody let me what I need to change in my code to get the desired output as mentioned above?
this is hard to split string directly.So, i will use the '\t' to replace
the whitespace if the whitespace is out of "". My code is below, you can try it, and maybe others will have better solution, we can discuss it too.
package com.code.stackoverflow;
/**
* Created by jiangchao on 2016/10/24.
*/
public class Main {
public static void main(String args[]) {
String str="broadcast message \"Shubham Agiwal\"";
char []chs = str.toCharArray();
StringBuilder sb = new StringBuilder();
/*
* false: means that I am out of the ""
* true: means that I am in the ""
*/
boolean flag = false;
for (Character c : chs) {
if (c == '\"') {
flag = !flag;
continue;
}
if (flag == false && c == ' ') {
sb.append("\t");
continue;
}
sb.append(c);
}
String []strs = sb.toString().split("\t");
for (String s : strs) {
System.out.println(s);
}
}
}
This is tedious but it works. The only problem is that if the whitespace in quotes is a tab or other white space delimiter it gets replaced with a space character.
String str = "broadcast message \"Shubham Agiwal\" better \"Hello java World\"";
Scanner scanner = new Scanner(str).useDelimiter("\\s");
while(scanner.hasNext()) {
String token = scanner.next();
if ( token.startsWith("\"")) { //Concatenate until we see a closing quote
token = token.substring(1);
String nextTokenInQuotes = null;
do {
nextTokenInQuotes = scanner.next();
token += " ";
token += nextTokenInQuotes;
}while(!nextTokenInQuotes.endsWith("\""));
token = token.substring(0,token.length()-1); //Get rid of trailing quote
}
System.out.println("Token is:" + token);
}
This produces the following output:
Token is:broadcast
Token is:message
Token is:Shubham Agiwal
Token is:better
Token is:Hello java World
public static void main(String[] arg){
String str = "broadcast message \"Shubham Agiwal\"";
//First split
String strs[] = str.split("\\s\"");
//Second split for the first part(Key part)
String[] first = strs[0].split(" ");
for(String st:first){
System.out.println(st);
}
//Append " in front of the last part(Value part)
System.out.println("\""+strs[1]);
}

Remove all words starting with "http" in a string?

I simply want to replace all words starting with "http" and ends with space or "\n" in a string
Example string is.
Full results below;
http://www.google.com/abc.jpg is a url of an image.
or some time it comes like https://www.youtube.com/watch?v=9Xwhatever this is an example text
Result of the string should be like
is a url of an image.
or some time it comes like this is an example text
I simply want to replace it with ""; i know the logic but don't know the function.
My logic is
string.startwith("http","\n")// starts with http and ends on next line or space
.replaceAll("")
public static void main(String[] args) {
String s = "https://www.google.com/abc.jpg is a url of an image.";
System.out.println(s.replaceAll("https?://.*?\\s+", ""));
}
O/P :
is a url of an image.
String.replaceAll() allows you to use a regex. In a regex, ^ allows you to capture the beginning of the String. Hence, you can do like that :
System.out.print("http://google-http".replaceAll("^http", ""));
result:
://google-http
The http at the beginning has be removed but not the one at the end.
public static void main(String[] args) {
String str = "https://www.google.com/abc.jpg is a url of an image.";
String subStr1 = "http://";
String substr2 = "https://";
String foundStr = "";
if(str.startsWith(subStr1)) {
foundStr = subStr1;
}
if (str.startsWith(subStr2)) {
foundStr = subStr2;
}
str = str.replaceAll(foundStr, "");
str = str.replaceAll(" ", "");
}

String Parsing in Java and android

I want to parse the data below in java. What approach shall I follow?
I want to neglect ; inside { }.
Thus Version, Content, Provide, UserConfig and Icon as name and corresponding values.
Version:"1";
Content:2013091801;
Provide:"Airtel";
UserConfig :
{
Checksum = "sha1-234448e7e573b6dedd65f50a2da72245fd3b";
Source = "content\\user.ini";
};
Icon:
{
Checksum = "sha1-a99f835tytytyt3177674489770e613c89390a8c4";
Source = "content\\resept_ico.bmp";
};
Here we can't use String.split(";") function.
It would have been lot more complex to convert using the Regex and then creating a method to extract the required fields,
What I did was converted the above mentioned input to Json compatible string and then used GSON library by google to parse the String to my customized class,
class MyVer
{
String Version;
long Content;
String Provide;
Config UserConfig;
Config Icon;
String Source;
}
class Config
{
String Checksum;
String Source;
}
public static void main(String[] args)
{
String s = "Version:\"1\";Content:2013091801;Provide:\"Airtel\";UserConfig :{ Checksum = \"sha1-234448e7e573b6dedd65f50a2da72245fd3b\"; Source = \"content\\user.ini\";};Icon:{ Checksum = \"sha1-a99f835tytytyt3177674489770e613c89390a8c4\"; Source = \"content\\resept_ico.bmp\";};";
String startingBracePattern = Pattern.quote("{");
String endBracePattern = Pattern.quote("}");
s=s.replaceAll(Pattern.quote("\\"), "\\\\\\\\"); //Replacing all the single \ with double \\
s = s.replaceAll("\\s*"+startingBracePattern +"\\s*", "\\{\""); //Replacing all the `spaces { spaces` with `{"` MEANS all the { to replace with {"
s = s.replaceAll(";\\s*"+endBracePattern +"\\s*;", "\\};"); //Replacing all the `; spaces } spaces ;` with `},"` MEANS all the ;}; to replace with };
s = "{\"" + s.substring(0, s.length() - 1) +"}"; //Removing last ; and appending {" and }
s = s.replaceAll("\\s*:", "\":"); // Replacing all the `space with :` with `":`
s = s.replaceAll("\\s*;\\s*", ",\""); //Replacing all the `spaces ; spaces` with `,"`
s = s.replaceAll("\\s*=\\s*", "\":"); //Replacing all the `spaces = spaces` with `":`
Gson gson = new Gson();
MyVer newObj = gson.fromJson(s, MyVer.class);
}
This converts and give you the object of MyVer and then you can access all the variables.
NOTE: You can alter the code little to replace all \r\n if they are present in your input variables. I have not used them and your actual data supplied in question in a single line for simplicity.
JSON sounds a lot easier in this case..
.. however, if you were to do this using regular expressions, one way would be:
for the simple cases (eg. version):
// look for Version: some stuff ;
Pattern versionPattern = Pattern.compile("Version\\s*:\\s*\"\\w+\"\\s*;");
// the whole big string you're looking in
String bigString = ...; // the entire string from before can go here
// create a matcher for the "version pattern"
Matcher versionMatcher = versionPattern.matcher(bigString);
// check if there's a match in the string
if(versionMatcher.find()) {
// get the matching substring
String matchingSubstring = bigString.substring(
versionMatcher.start(),
versionMatcher.end()
);
// we need the area between the quotes
String version = matchingSubstring.split("\"")[1];
// do something with it
...
}
for the harder (multi-line) cases (eg. UserConfig):
// look for UserConfig : { some stuff };
Pattern userconfigPattern = Pattern.compile("UserConfig\\s*:\\s*{[^}]*};", Pattern.DOTALL);
// create a matcher for the "user config pattern"
Matcher userconfigMatcher = userconfigPattern.matcher(bigString);
// check if there's a match in the string
if(userconfigMatcher.find()) {
// get the matching substring
String matchingSubstring = bigString.substring(
userconfigMatcher.start(),
userconfigMatcher.end()
);
// we need the area between the curly braces
String version = matchingSubstring.split("[{}]")[1];
// do something with it
...
}
EDIT: this is probably an easier way
// split the input string into fields
String[] fields = bigString.split("[^:]+:([^{;]+;)|({[^}]+};)");
// for each key-value pair
for(String field : fields) {
// the key and value are separated by colons
String parts = field.split(":");
String key = parts[0];
String value = parts[1];
// do something with them, or add them to a map
...
}
This last way splits the input string based on the assumption that each key-value pair consists of:
some (non-colon) characters at the start, followed by
a colon,
either
-> some characters that are not curly braces or semi-colons (for simple attributes), or
-> curly braces containing some characters that are not curly braces
a semi-colon
Here is json solution
str = "{" + str.substring(0, str.lastIndexOf(";")).replace(";\n}", "}") + "}";
try {
JSONObject json = new JSONObject(str);
String version = json.getString("Version");
JSONObject config = json.getJSONObject("UserConfig");
String source = config.getString("Source");
} catch (JSONException e) {
e.printStackTrace();
}
since ";" should not be in front of "}"
Source = "content\\resept_ico.bmp";
}
we need remove them

Removing link from Text in Java?

I need to change somethign like this -> Hello, go here http://www.google.com for your ...
grab the link, and change it in a method i made, and replace it back into the string like this
-> Hello, go here http://www.yahoo.com for your...
Here is what i have so far:
if(Text.toLowerCase().contains("http://"))
{
// Do stuff
}
else if(Text.toLowerCase().contains("https://"))
{
// Do stuff
}
All i need to do is change the URL in the String to something different. The Url in the String will not always be http://www.google.com, so i can not just say replace("http://www.google.com","")
Use regex:
String oldUrl = text.replaceAll(".*(https?://)www((\\.\\w+)+).*", "www$2");
text = text.replaceAll("(https?://)www(\\.\\w+)+", "$1" + traslateUrl(oldUrl));
Note: code changed to meet extra requirements in comments below.
you can grab the link from the string using below code. I assumed the string will contain only .com domain
String input = "Hello, go here http://www.google.com";
Pattern pattern = Pattern.compile("http[s]{0,1}://www.[a-z-]*.com");
Matcher m = pattern.matcher(input);
while (m.find()) {
String str = m.group();
}
Have you tried something like:
s= s.replaceFirst("http:.+[ ]", new link);
This will find any word beginning with http up till the first white space and replace it with whatever you want
if you want to keep the link then you can do:
String oldURL;
if (s.contains("http")) {
String[] words = s.split(" ");
for (String word: words) {
if (word.contains("http")) {
oldURL = word;
break;
}
}
//then replace the url or whatever
}
You can try this
private String removeUrl(String commentstr)
{
String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(commentstr);
int i = 0;
while (m.find()) {
commentstr = commentstr.replaceAll(m.group(i),"").trim();
i++;
}
return commentstr;
}

Categories