Regex and find in text file [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code :
package ggg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
public class regex {
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "This order was placed FRO-DDA-6666666 %10.25 %10.12 FRO-DDA-8888888 for QT3000! OK?";
String pattern = "\\d+\\.\\d{2}";
String pattern2 = "\\d{7}";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
Pattern t = Pattern.compile(pattern2);
// Now create matcher object.
Matcher m = r.matcher(line);
Matcher g = t.matcher(line);
try {
PrintWriter writer = new PrintWriter("C:\\Users\\John\\workspace\\ggg\\src\\ggg\\text.txt", "UTF-8");
for (int i = 1; m.find() && g.find(); i++) {
writer.println(g.group(0)+"->"+m.group(0));
}
writer.close();
} catch (IOException ex) {}
}
}
And result is:
6666666->10.25
8888888->10.12
I want to write a simple code to read text.txt file and if "8888888" exist in this file then print what is the front of "8888888->", What should I do ?
For example in our result 10.12 is front of 888888->

Add this to your code after building the file:
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\John\\workspace\\ggg\\src\\ggg\\text.txt"));
String myLine;
while ((myLine = br.readLine()) != null) {
if(myLine.contains("8888888"))
System.out.println(myLine.substring(myLine.indexOf(">")+1));
}
br.close();

Related

How to replace a line with something? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So my program needs to overwrite e.g line 5 in a file. Just the 5th line, keep the others.
We don't know what is the content of line 5.
But I have no idea how to do it, can't found anything about how to do this with BufferedWriter and FileWriter.
I can't write there a code, because.. I just don't know how to do it.:/
A sample solution could look like this
package teststuff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Btest {
public static void main(String args[])
{
try
{
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "", fivthLine = "";
int x=0;
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
if(x == 4)
{
fivthLine = line;
}
x++;
}
reader.close();
String newtext = oldtext.replaceAll(fivthLine, "blah blah blah");
FileWriter writer = new FileWriter("test.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Note that this is a combination of what Emmanuel wrote and this
It will also replace whats written in the 5th line everywhere on the file, so that another line containing the same content of line 5 will also be overwritten with
"blah blah blah"
by first you can start looking for "How to count lines on a file" like this i found
https://www.geeksforgeeks.org/counting-number-lines-words-characters-paragraphs-text-file-using-java/
Then add counter++ each time you pass a line, when (counter == 5)
then do whatever you need to do..
This is a very simple example of replacing a given line in a file:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class LineReplaceTest
{
public static void main(String... args)
throws Exception
{
int lineToReplace = 5;
String replacementText = "This is a different line";
Path input = Paths.get("input.txt");
Path output = Paths.get("output.txt");
// Use try-with-resources to ensure our readers & writers are closed
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
int lineNumber = 0;
// While there is a line to read from input...
while ((line = reader.readLine()) != null) {
lineNumber++;
// Write out either the line from the input file or our replacement line
if (lineNumber == lineToReplace) {
writer.write(replacementText);
} else {
writer.write(line);
}
writer.newLine();
}
}
// Once we're done, overwrite the input file
Files.move(output, input);
}
}
It ignores several important things line error handling and platform-specific newline handling, but it should at least get you started.

regular expression to replace anything but unicode letters in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My text file is in the following format having different type of strings such as below:
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
I would like to remove everything except simple words such as the ones below.
smoldering
temperature
That is if a word is even followed by a comma (e.g. smoldering,), I would remove it.
I tried to remove the digits for a start with MyString.replaceAll("^\\d", " ") but even that is not working.
If you load the entire file into memory, with line breaks, you can use a regex like this:
text = text.replaceAll("(?m)^.*[^a-zA-Z\r\n].*(?:\R|$)", "")
Output
candle
smoldering
temperature
For demo see regex101.
It would however be better to do the filtering while you load the text file:
Pattern simpleWord = Pattern.compile("\\p{L}+"); // one or more Unicode letters
try (BufferedReader in = Files.newBufferedReader(Paths.get("path/to/file.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
if (simpleWord.matcher(line).matches()) {
// found simple word
}
}
}
If you want the simple words in a list, you can simplify that with Java 8 stream:
List<String> simpleWords;
try (Stream<String> lines = Files.lines(Paths.get("path/to/file.txt"))) {
simpleWords = lines.filter(Pattern.compile("^\\p{L}+$").asPredicate())
.collect(Collectors.toList());
}
This solution will iterate over the input.txt lines and paste them into output.txt if they match certain regex. After that it will remove output.txt and rename it with input.txt original file.
Class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Pattern;
public class ReplaceWithRegex {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (Pattern.matches("^[a-zA-Z]+$", line)) {
writer.write(line);
writer.newLine();
}
}
}
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename output to input");
}
} else {
throw new IOException("Could not delete original input file ");
}
}
}
Input.txt
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
Input.txt after execution:
candle
smoldering
temperature
Assuming lines are delimiters:
myString.replaceAll("^[^a-z&&[^A-Z]]*$", "");

How to add a tumblr feed into a java swing project [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm making a launcher for my game using Java Swing. I need a way to add a tumblr/wordpress feed onto the launcher. An example would be the minecraft launcher (If you don't know what it looks like, go to this link).
I was also thinking RSS could be useful because I've seen that mentioned on feeds and stuff like this so if there's a simple way with that then that'd be helpful too.
Anyway, how would I do this?
EDIT: How would I use jsoup in Swing?
Here's an example I have used to parse data from a page
private static final String url = "website";
public void getLatestUpdate() throws IOException {
try {
URL addr = new URL(url);
URLConnection con = addr.openConnection();
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Pattern p = Pattern.compile("<span itemprop=.*?</span>");
Pattern p2 = Pattern.compile(">.*?<");
Matcher m = p.matcher(inputLine);
Matcher m2;
while (m.find()) {
m2 = p2.matcher(m.group());
while (m2.find()) {
data.add(m2.group().replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("#", "").replaceAll(";", "").replaceAll("3", "3"));
}
}
}
in.close();
addr = null;
con = null;
message("(" + data.get(3) + ")" + ", at " + data.get(4));
} catch (Exception e) {
System.out.println("Error getting data from website.");
e.printStackTrace();
}
}

Retrieving a string by line number? Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}

How to fill ArrayList in a loop, when size is not known? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to fill members of some objects, but I don't know how many are them. That's why I'm using ArrayList because of dynamic size. But I don't know how to fill these objects in ArrayList. I'm reading line by line from file and if I found my match pattern, I have to create new object and fill it with data.
//read data from file to BufferedReader, that we can read out single line by line
BufferedReader mBufferedReader = new BufferedReader(new FileReader(mFile));
String line;
while ((line = mBufferedReader.readLine()) != null) {
//pattern "name" for searching points
Pattern pattern = Pattern.compile("\"(.*?)\"");
//array of delimited Strings separated with comma
String[] delimitedStrings = line.split(",");
//if we find "name" of point, get code, lat and lon of that point
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String name = delimitedStrings[0];
mData.add(new myData().name = name);
String code = delimitedStrings[1];
mData.add(new myData().code = code);
}
}
myData class has members String name, String code for example. I need something like this with add method, but that is not working. Thanks!
A bit vague but maybe you meant this
if (matcher.find()) {
String name = delimitedStrings[0];
String code = delimitedStrings[1];
mTaskData.add(new MyData(name, code));
}
where MyData class has a constructor defined as
public class MyData {
private String name;
private String code;
public MyData (String name, String code) {
this.name = name;
this.code = code;
}
// getters/setters()
}
Also, the Pattern doesn't change so should be moved out of the file reader loop.
// compile the pattern just once (outside the loop)
Pattern pattern = Pattern.compile("\"(.*?)\"");
while ((line = mBufferedReader.readLine()) != null) {
This won't compile:
if (matcher.find()) {
String name = delimitedStrings[0];
mTaskData.add(new myData().name = name);
String code = delimitedStrings[1];
mTaskData.add(new myData().code = code);
}
should be like this:
if (matcher.find()) {
String name = delimitedStrings[0];
myData md = new myData();
md.name = name; // or use setter like md.setName(name)
mTaskData.add(md);
String code = delimitedStrings[1];
md.code = code;
mTaskData.add(md);
}
List<mData> mData = new ArrayList<>();
mData.add(new mData(code));
make a constructor in mData with parameter String code

Categories

Resources