Deleting exact match String from text file [duplicate] - java

This question already has answers here:
Find a line in a file and remove it
(17 answers)
Closed 1 year ago.
I am trying to remove a specific string in my text file. Current code gets the line one by one until 50 is hit. I am trying to remove the string (EXACT MATCH!) in the notepad, but not sure how to do so.
Scanner input = new Scanner(new File("C:\\file.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 50) {
counter++;
String tempName = input.nextLine();
//perform my custom code here
//somehow delete tempName from the text file (exact match)
}
I have tried input.nextLine().replaceFirst(tempName, ""); without any luck

If you are using Java 8, You can do something like below using java.nio package:
Path p = Paths.get("PATH-TO-FILE");
List<String> lines = Files.lines(p)
.map(str -> str.replaceFirst("STRING-TO-DELETE",""))
.filter(str -> !str.equals(""))
.collect(Collectors.toList());
Files.write(p, lines, StandardCharsets.UTF_8);

Below line replaces "the" with "**"
Pattern pattern = Pattern.compile("the", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(tempName);
String repalcedvalue = matcher.replaceAll("**");

Related

Parse string value from URL

I have a string (which is an URL) in this pattern https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg
now I want to clip it to this
media/93939393hhs8.jpeg
I want to remove all the characters before the second last slash /.
i'm a newbie in java but in swift (iOS) this is how we do this:
if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
print(trimmedString) // "output = media/93939393hhs8.jpeg"
}
Basically, I'm removing everything from this Url expect of last 2 item and then.
I'm joining those 2 items using /.
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Are you familiar with Regex? Try to use this Regex (explained in the link) that captures the last 2 items separated with /:
.*?\/([^\/]+?\/[^\/]+?$)
Here is the example in Java (don't forget the escaping with \\:
Pattern p = Pattern.compile("^.*?\\/([^\\/]+?\\/[^\\/]+?$)");
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(m.group(1));
}
Alternatively there is the split(..) function, however I recommend you the way above. (Finally concatenate separated strings correctly with StringBuilder).
String part[] = string.split("/");
int l = part.length;
StringBuilder sb = new StringBuilder();
String result = sb.append(part[l-2]).append("/").append(part[l-1]).toString();
Both giving the same result: media/93939393hhs8.jpeg
string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));
or
Use Split and add last 2 items
string[] arr=url.split("/");
string result= arr[arr.length-2]+"/"+arr[arr.length-1]
public static String parseUrl(String str) {
return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}

modify regexp to detect all url links [duplicate]

This question already has answers here:
Validating URL in Java
(11 answers)
Closed 9 years ago.
i have method which can return me to array of links in string, but this work only if link have 'http' or 'www' prefix ( http:// site.com or www.site.com) . and also need to detect links without prefix just site.com
Please help me
ArrayList retrieveLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|https://|www[.])[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
char[] stringArray1 = urlStr.toCharArray();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
{
char[] stringArray = urlStr.toCharArray();
char[] newArray = new char[stringArray.length-2];
System.arraycopy(stringArray, 1, newArray, 0, stringArray.length-2);
urlStr = new String(newArray);
// System.out.println("Finally Url ="+newArray.toString());
}
//System.out.println("...Url..."+urlStr);
links.add(urlStr);
}
return links;
}
Not commenting on the rest of the source code
Make the prefix optional, using a ? after the group that declares the possible prefixes.
String regex = "\\(?\\b(http://|https://|www[.])?[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
See live test here.

Best way to convert list to comma separated string in java [duplicate]

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 9 years ago.
I have Set<String> result & would like to convert it to comma separated string. My approach would be as shown below, but looking for other opinion as well.
List<String> slist = new ArrayList<String> (result);
StringBuilder rString = new StringBuilder();
Separator sep = new Separator(", ");
//String sep = ", ";
for (String each : slist) {
rString.append(sep).append(each);
}
return rString;
Since Java 8:
String.join(",", slist);
From Apache Commons library:
import org.apache.commons.lang3.StringUtils
Use:
StringUtils.join(slist, ',');
Another similar question and answer here
You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.
Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");
String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
total += s.length();
}
StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
sb.append(separator).append(s);
}
String result = sb.substring(separator.length()); // remove leading separator
The Separator you are using is a UI component. You would be better using a simple String sep = ", ".

Storing in String [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the most elegant way to concatenate a list of values with delimiter in Java?
I have 3 different words listed in property file in 3 different lines.
QWERT
POLICE
MATTER
I want to read that property file and store those 3 words in String, not in aarylist separated by whitespace. The output should look like this
String str = { QWERT POLICE MATTER}
Now I used the follwoing code and getting the output without white space in between the words:
String str = {QWERTPOLICEMATTER}. What should I do to the code to get the string result with words separated by whitespace.
FileInputStream in = new FileInputStream("abc.properties");
pro.load(in);
Enumeration em = pro.keys();
StringBuffer stringBuffer = new StringBuffer();
while (em.hasMoreElements()){
String str = (String)em.nextElement();
search = (stringBuffer.append(pro.get(str)).toString());
Try:
search = (stringBuffer.append(" ").append(pro.get(str)).toString());
Just append a blank space in your loop. See the extra append below:
while (em.hasMoreElements()){
String str = (String)em.nextElement();
search = (stringBuffer.append(pro.get(str)).toString());
if(em.hasNext()){
stringBuffer.append(" ")
}
}

Splitting Java string with quotation marks [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you recommend a Java library for reading (and possibly writing) CSV files?
I need to split the String in Java. The separator is the space character.
String may include the paired quotation marks (with some text and spaces inside) - the whole body inside the paired quotation marks should be considered as the single token.
Example:
Input:
token1 "token 2" token3
Output: array of 3 elements:
token1
token 2
token3
How to do it?
Thanks!
Split twice. First on quotes, then on spaces.
Assuming that the other solutions will not work for you, because they do not properly detect matching quotes or ignore spaces within quoted text, try something like:
private void addTokens(String tokenString, List<String> result) {
String[] tokens = tokenString.split("[\\r\\n\\t ]+");
for (String token : tokens) {
result.add(token);
}
}
List<String> result = new ArrayList<String>();
while (input.contains("\"")) {
String prefixTokens = input.substring(0, input.indexOf("\""));
input = input.substring(input.indexOf("\"") + 1);
String literalToken = input.substring(0, input.indexOf("\""));
input.substring(input.indexOf("\"") + 1);
addTokens(prefixTokens, result);
result.add(literalToken);
}
addTokens(input, result);
Note that this won't handle unbalanced quotes, escaped quotes, or other cases of erroneous/malformed input.
import java.util.StringTokenizer;
class STDemo {
static String in = "token1;token2;token3"
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, ";");
while(st.hasMoreTokens()) {
String val = st.nextToken();
System.out.println(val);
}
}
}
this is easy way to string tokenize

Categories

Resources