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(" ", "");
}
Related
I was trying to replace/remove any string between - <branch prefix> /
Example:
String name = Application-2.0.2-bug/TEST-1.0.0.zip
expected output :
Application-2.0.2-TEST-1.0.0.zip
I tried the below regex, but it's not working accurate.
String FILENAME = 2.2.1-Application-2.0.2-bug/TEST-1.0.0.zip
println(FILENAME.replaceAll(".+/", ""))
There can be many ways e.g. you can replace \w+\/ with a "". Note that \w+ means one or more word characters.
Demo:
public class Main {
public static void main(String[] args) {
String FILENAME = "Application-2.0.2-bug/TEST-1.0.0.zip";
FILENAME = FILENAME.replaceAll("\\w+\\/", "");
System.out.println(FILENAME);
}
}
Output:
Application-2.0.2-TEST-1.0.0.zip
ONLINE DEMO
I have a string:
100-200-300-400
i want replace the dash to "," and add single quote so it become:
'100','200','300','400'
My current code only able to replace "-" to "," ,How can i plus the single quote?
String str1 = "100-200-300-400";
split = str1 .replaceAll("-", ",");
if (split.endsWith(","))
{
split = split.substring(0, split.length()-1);
}
You can use
split = str1 .replaceAll("-", "','");
split = "'" + split + "'";
As an alternative if you are using java 1.8 then you could create a StringJoiner and split the String by -. This would be a bit less time efficient, but it would be more safe if you take, for example, a traling - into account.
A small sample could look like this.
String string = "100-200-300-400-";
String[] splittet = string.split("-");
StringJoiner joiner = new StringJoiner("','", "'", "'");
for(String s : splittet) {
joiner.add(s);
}
System.out.println(joiner);
This will work for you :
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
System.out.println(s.replaceAll("(\\d+)(-|$)", "'$1',").replaceAll(",$", ""));
}
O/P :
'100','200','300','400'
Or (if you don't want to use replaceAll() twice.
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
s = s.replaceAll("(\\d+)(-|$)", "'$1',");
System.out.println(s.substring(0, s.length()-1));
}
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;
}
Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");
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.