I have to remove this.
String removeKey = "problem_keys";
Code
public class Solution {
public static void main(String args[]) {
String removeKey = "problem_keys";
String url = "{\"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;problem_keys:1,35,3,4,5,6,7,15,16,11,12,16;\";}";
StringBuffer sb = new StringBuffer(url);
removeKey(sb, removeKey);
System.out.println(sb.toString());
}
public static void removeKey(StringBuffer url, String removeKey) {
int sIndex = url.indexOf(removeKey);
while (url.charAt(sIndex) != ';') {
url.deleteCharAt(sIndex);
}
url.deleteCharAt(sIndex);
}
}
Expected output.
{"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;}";
Guessing you want also to remove the "values", using java 8:
String toRemove = Arrays.stream(url.split(";")).filter(part -> part.contains(removeKey)).findFirst().orElse("");
String newUrl = url.replace(toRemove, "");
System.out.println(newUrl);
Speaking about the delimeters you can consider adding ";" to the toRemove string in a conditional block.
If you're aim is only to get rid of the string removeKey you can just:
url.replace(removeKey, "");
I would go with this:
String removeKey = "problem_keys;";
url = url.replace(removeKey, "") // Replace the whole "problem_keys;" string with an empty string
Related
This question already has answers here:
What is the fastest way to get the domain/host name from a URL?
(8 answers)
Closed 3 years ago.
Im trying to split URLs, for example https://stackoverflow.com/questions/ and take only stackoverflow.com. How can I do this in Java without using the built in function getHost()?
If you can put your URL into a String , there is this option :
public static void main(String []args){
String str ="https://stackoverflow.com/questions/";
String[] parts = str.split("/");
String part1 = parts[0]; //https:
String part2 = parts[1]; //'nothing'
String part3 = parts[2]; //stackoverflow.com
String part4 = parts[3]; //questions
}
One thing you can do is use String#replaceAll. I know it's not what you want but off the bat it's a decent way to do it.
String uri = "https://stackoverflow.com/questions/";
if (uri.contains("https://")) {
uri = uri.replaceAll("https://", "");
}
if (uri.contains("http://")) {
uri = uri.replaceAll("http://", "");
}
int indexOfBackwardsSlash = uri.indexOf("/");
if (indexOfBackwardsSlash != -1) {
uri = uri.substring(0, indexOfBackwardsSlash);
}
Use URI#getPath.
URI uri = URI.create("https...");
String path = uri.getPath();
You could also use regular expressions:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UrlRegex {
public static void main(String []args){
String url = "https://stackoverflow.com/questions/";
Pattern pat = Pattern.compile("//([^/]*)"); //match everything between "//" and "/"
Matcher m = pat.matcher(url);
if (m.find()) {
String hostname = m.group(1);
}
}
}
Here you go :
Pattern pattern = Pattern.compile("^(?:(?:http)s?://)?(?<hostGroup>[^/:]+).*");
Matcher matcher = pattern.matcher("https://stackoverflow.com/questions/");
if (matcher.matches()) {
System.out.println(matcher.group("hostGroup"));
} else {
System.out.println("Not found! Invalid URL ^^");
}
The above will find stackoverflow.com for the following urls strings :
https://stackoverflow.com/questions/
http://stackoverflow.com/questions/
stackoverflow.com/questions/
stackoverflow.com:80/questions/
stackoverflow.com/
stackoverflow.com
I guess that's for practicing regex ? Otherwise, prefer using the standard APIs whenever possible - (in your case URI#getHost() !)
Cheers!
If you are sure that you are getting the proper URL format than you can just substring it preferred places.
public static void main(String[] args) {
String url = "https://stackoverflow.com/questions/";
System.out.println(getHostFast(url));
}
public static String getHostFast(String url) {
String subbed = url.substring(url.indexOf('/') + 2);
return subbed.substring(0, subbed.indexOf('/'));
}
The error prof method would need to contain additional check (for example if the next '/' exists after dropping http://.
I have a string (URL) like this:
"https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp"
I need to extract the last part only i.e. 02_Cuppy_lol.webp.
How can I do that?
Thanks!
You can use substring() and lastIndexOf() here:
String value = completeString.substring(completeString.lastIndexOf("/") + 1);
You can split this text/url and get last part, for example:
String url = "https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] splittedUrl = url.split("/");
String lastPart = splittedUrl[splittedUrl.length()-1)];
you can use the method split().follow this example
public class Demo {
public static void main(String args[]){
String str ="https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] temp=str.split("/");
int lastIndex =temp.length-1;
String lastPart = temp[lastIndex];
System.out.println(lastPart);
}
}
Output-:
02_Cuppy_lol.webp
I have to create file with user define name. If User can use the special character then i want to replace that special character with my specific string. i found the method like this.
String replaceString(String string) {
return string.replaceAll("special_char","");
}
but how to use this method.?
relpaceAll method is required regular expression and replace string.
string.replaceAll("regularExpression","replaceString");
You can use this regular expression :
"[;\\/:*?\"<>|&']"
e.g.
String replaceString(String string) {
return string.replaceAll("[;\\/:*?\"<>|&']","replaceString");
}
Try
regular expression
static String replaceString(String string) {
return string.replaceAll("[^A-Za-z0-9 ]","");// removing all special character.
}
call
public static void main(String[] args) {
String str=replaceString("Hello\t\t\t.. how\t\t are\t you."); // call to replace special character.
System.out.println(str);
}
output:
Hello how are you
use below function to replace your string
public static String getString(String p_value)
{
String p_value1 = p_value;
if(p_value1 != null && ! p_value1.isEmpty())
{
p_value1 = p_value1.replace("Replace string from", "Replace String to");
return p_value1;
}
else
{
return "";
}
}
example
Replace string from = "\n";
Replace String to = "\r\n";
after using above function \n is replace with \r\n
**this method make two line your string data after specific word **
public static String makeTwoPart(String data, String cutAfterThisWord){
String result = "";
String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
String va12 = data.substring(val1.length(), data.length());
String secondWord = va12.replace(cutAfterThisWord, "");
Log.d("VAL_2", secondWord);
String firstWord = data.replace(secondWord, "");
Log.d("VAL_1", firstWord);
result = firstWord + "\n" + secondWord;
return result;
}
I have string with value as ||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||
I am trying to write code which should remove duplicates and return the unique values retaining the demiliters like this ||HelpDesk||IT Staff||Admin||Audit||
My code is using HashSet to remove duplicates but the problem is it is removing delimiters. How can I retain delimiters by removing duplicate values only.
Below is my code after removing duplicates and adding back delimiters. But not sure if there is easy way of doing this.
public static void main(String[] args) {
TestDuplicates testDuplicates = new TestDuplicates();
String bRole = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||";
List<String> listWithoutDuplicates = new ArrayList<String>();
String noDup = "";
List<String> splittedStringList =
new ArrayList<String>();
SplitOperations splitOperations =
new SplitOperations();
splittedStringList =
splitOperations.splitString(bRole);
for (int i = 0; i < splittedStringList.size(); i++) {
HashSet<String> listToSet = new HashSet<String>(splittedStringList);
listWithoutDuplicates = new ArrayList<String>(listToSet);
}
for(int i=0;i<listWithoutDuplicates.size();i++){
noDup = noDup + "||"+listWithoutDuplicates.get(i);
System.out.println(listWithoutDuplicates.get(i));
}
System.out.println("No Duplicate is::"+ noDup+"||");
}
Thanks
You could use a LinkedHashSet to preserve insertion order. Once you splitted the String by "||" just add the delimiters when constructing back the String.
String s = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||";
Set<String> set = new LinkedHashSet<>(Arrays.asList(s.split(Pattern.quote("||"))));
String noDup = "||";
for(String st : set) {
if(st.isEmpty()) continue;
noDup += st+"||";
}
Or using the new java 8 Stream API :
String noDup = "||"+
Arrays.stream(s.split(Pattern.quote("||")))
.distinct()
.filter(st -> !st.isEmpty()) //we need to remove the empty String produced by the split
.collect(Collectors.joining("||"))+"||";
Both approaches yield the same result (||HelpDesk||IT Staff||Admin||Audit||).
public String removeDublicate () {
String str = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||";
String split[] = str.split("\\|\\|");
String newStr = "";
for (String s : split) {
if (!s.isEmpty() && !newStr.contains(s)) {
newStr += "||" + s;
}
}
newStr += "||";
return newStr;
}
Something like that? str could be an argument.
Edit #1
If you want to get rid of && !newStr.contains(s) you can use a HashSet<String> instead. I think that is overkill however. .contains(s) will do the trick when the string is small such as this.
This should work, also it will maintain sequence of elements if you want. Note that I have not written code to put delimiters again.
public static void main(String s[]){
String a = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||";
a = a.replaceAll("\\|\\|",",");
String arr[] = a.split(",");
//linked hash set in case you want to maintain the sequence of elements
Set<String> set = new LinkedHashSet<String>(Arrays.asList(arr));
set.remove("");
System.out.println(set);
//Iterate through the set and put your delimiters here again
}
Using Guava lib it's a one liner:
Joiner.on("||").skipNulls(Splitter.on("||").trimResults().split(<target_string>);)
Here is my attempt at it:
import java.util.*;
public class Seperator {
public static void main(String[] args) {
String bRole = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||";
List<String> listWithoutDuplicates = new ArrayList<String>();
String noDup = "";
List<String> splittedStringList = new ArrayList<String>();
splittedStringList = Arrays.asList(bRole.split("\\|\\|"));
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(splittedStringList);
noDup = Seperator.join(listToSet, "||");
System.out.println("No Duplicate is::"+ noDup+"||");
}
public static String join(Set<String> set, String sep) {
String result = null;
if(set != null) {
StringBuilder sb = new StringBuilder();
Iterator<String> it = set.iterator();
if(it.hasNext()) {
sb.append(it.next());
}
while(it.hasNext()) {
sb.append(sep).append(it.next());
}
result = sb.toString();
}
return result;
}
}
LinkedHashSet are mainly used to preserve the order and ofcourse get uniques elements. Joining is pretty standard, but we can use Google's Guava Library also (Joiner):
So, instead of Seperator.join(listToSet, "||");
You'll have: Joiner.on("||").join(listToSet);
Here's a regex-based one liner:
str = str.replaceAll("(\\|[^|]+)(?=.*\\1\\|)", "");
This works by replacing every term that is followed by itself somewhere ahead via a look ahead assertion that uses a back reference.
Here's a non-regex java 8 one liner:
Arrays.stream(str.substring(1).split("[|]")).distinct().collect(Collectors.joining("|", "|", "|"));
I want to parse HTML String by extracting only <form> ... </form>. All other stuff don't needed and I can remove it.
Today I have some helpers to remove through replaceAll special tag content like:
/** remove form */
String newString = string.replaceAll("(?s)<form.*?</form>", "");
(?s)<form.*?</form>
removes form tags. But I need vice versa, remove everything except form.
How can I fix it?
See my Gskinner example
Try below code.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Client {
private static final String PATTERN = "<form>(.+?)</form>";
private static final Pattern REGEX = Pattern.compile(PATTERN);
private static final boolean ONLY_TAG = true;
public static void main(String[] args) {
String text = "Hello <form><span><table>Hello Rais</table></span></form> end";
System.out.println(getValues(text, ONLY_TAG));
System.out.println(getValues(text, !ONLY_TAG));
}
private static String getValues(final String text, boolean flag) {
final Matcher matcher = REGEX.matcher(text);
String tagValues = null;
if (flag) {
if (matcher.find()) {
tagValues = "<form>" + matcher.group(1) + "</form>";
}
} else {
tagValues = text.replaceAll(PATTERN, "");
}
return tagValues;
}
}
You will get below output
<form><span><table>Hello Rais</table></span></form>
Hello end
The below code will give you a direction in what you are looking for:
String str = "<html><form>test form</form></html>";
String newString = str.replaceAll("[^<form</form>]+|((?s)<form.*?</form>)", "$1");
System.out.println(newString);