I'm using regex to read data from a file but I'm having trouble using the data I'm reading.
here is my code:
File file = new File(eventsFile);
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()){
String eventLine = sc.nextLine();
Pattern pattern = Pattern.compile("^Event=(?<event>[^,]*),time=(?<time>[^,]*)(,rings=(?<rings>[^,]*))?$");
Matcher matcher = pattern.matcher(eventLine);
while (matcher.find()) {
System.out.print(matcher.group("event") + " " + matcher.group("time"));
String eventName = matcher.group("event");
int time = Integer.parseInt(matcher.group("time"));
Class<?> eventClass = Class.forName(eventName);
Constructor<?> constructor = eventClass.getConstructor(long.class);
Event event = (Event) constructor.newInstance(time);
addEvent(event);
if (matcher.group(4) != null) {
System.out.println(" " + matcher.group(4));
} else {
System.out.println();
}
}
}
The print statements are there just temporarily to make sure the scanning of the file and regex work. what i'm trying to accomplish is use matcher.group(1) and matcher.group(2) as follows addEvent(new eventname(time)) where eventname is matcher.group(1) and time is matcher.group(2)
I tried creating variables to store group(1) and 2 and use them in addEvent but that didn't really work. So any ideas on how to approach such an issue?
EDIT:
Example of text file
Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=10000
Event=ThermostatDay,time=12000
Event=Bell,time=9000,rings=5
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=20000
Event=FansOn,time=7000
Event=FansOff,time=8000
I'm trying to reach a situation where i would be running for an addEvent function for each of these lines in the text file that would follow this example addEvent(new ThermostatNight(0));
Related
I'm trying to match exact AdvanceJava keyword with the given inputText string but it executes both if and else condition,instead of I want only AdvanceJava keyword matched.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List keywordsList = new ArrayList<>();//where keywordsList{advance,core,programming} -> keywordlist fetch
// from database
Enumeration e = Collections.enumeration(keywordsList);
int size = keywordsList.size();
while (e.hasMoreElements()) {
for (int i = 0; i < size; i++) {
String s1 = (String) keywordsList.get(i);
if (inputText.contains(s1) && inputText.contains(match)) {
System.out.println("Yes we providing " + s1);
} else if (!inputText.contains(s1) && inputText.contains(match)) {
System.out.println("Yes we are working on java");
}
}
break;
}
Thanks
you can simply do this by using pattern and matcher classes
Pattern p = Pattern.compile("java");
Matcher m = p.matcher("Print this");
m.find();
If you want to find multiple matches in a line, you can call find() and group() repeatedly to extract them all.
Here's how you can achieve what you seek using pattern matching.
In the first example I have taken your input text as it is. This only improves your algorithm which has O(n^2) performance.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List<String> keywordsList = Arrays.asList("advance", "core", "programming");
for (String keyword : keywordsList) {
Pattern p = Pattern.compile(keyword.concat(match));
Matcher m = p.matcher(inputText);
//System.out.println(m.find());
if (m.find()) {
System.out.println("Yes we are providing " + keyword.concat(match));
}
}
But we can improve this in to a better implementation. Here's a more generic version of the above implementation. This code doesn't manipulate the input text before matching, rather we provide a more generic regular expression which ignores spaces and matches case insensitive manner.
String inputText = "i want to know related to Advance java";
String match = "java";
List<String> keywordsList = Arrays.asList("advance", "core", "programming");
for (String keyword : keywordsList) {
Pattern p = Pattern.compile(MessageFormat.format("(?i)({0}\\s*{1})", keyword, match));
Pattern p1 = Pattern.compile(MessageFormat.format("(?i)({0})", match));
Matcher m = p.matcher(inputText);
Matcher m1 = p1.matcher(inputText);
//System.out.println(m.find());
if(m.find()) {
System.out.println("Yes we are providing " + keyword.concat(match));
} else if(m1.find()) {
System.out.println("Yes we are working with " + match);
}
}
#sithum - Thanks but it executes both condition of if else in output.Please refer Screen shot which I attached here.
I applied following logic and it works fine. please refer it , Thanks.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List<String> keywordsList = session.createSQLQuery("SELECT QUESTIONARIES_RAISED FROM QUERIES").list(); // Fetch values from database (advance,core,programming)
String uniqueKeyword=null;
String commonKeyword= null;
int size =keywordsList.size();
for(int i=0;i<size;i++){
String s1 = (String) keywordsList.get(i);//get values one by one from list
if(inputText.contains(match)){
if(inputText.contains(s1) && inputText.contains(match)){
Queries q1 = new Queries();
q1.setQuestionariesRaised(s1); //set matched keyword to getter setter method
keywordsList1=session.createQuery("from Queries sentence where questionariesRaised='"+q1.getQuestionariesRaised()+"'").list(); // based on matched keyword fetch according to matched keyword sentence which stored in database
for(Queries ob : keywordsList1){
uniqueKeyword= ob.getSentence().toString();// Store fetched sentence to on string variable
}
break;
}else {
commonKeyword= "java only";
}
}
}}
if(uniqueKeyword!= null){
System.out.println("Yes we providing......................" + uniqueKeyword);
}else if(commonKeyword!= null){
System.out.println("Yes we providing " + commonKeyword);
}else{
}
I'm working on a simple bot for discord and the first pattern reading works fine and I get the results I'm looking for, but the second one doesn't seem to work and I can't figure out why.
Any help would be appreciated
public void onMessageReceived(MessageReceivedEvent event) {
if (event.getMessage().getContent().startsWith("!")) {
String output, newUrl;
String word, strippedWord;
String url = "http://jisho.org/api/v1/search/words?keyword=";
Pattern reading;
Matcher matcher;
word = event.getMessage().getContent();
strippedWord = word.replace("!", "");
newUrl = url + strippedWord;
//Output contains the raw text from jisho
output = getUrlContents(newUrl);
//Searching through the raw text to pull out the first "reading: "
reading = Pattern.compile("\"reading\":\"(.*?)\"");
matcher = reading.matcher(output);
//Searching through the raw text to pull out the first "english_definitions: "
Pattern def = Pattern.compile("\"english_definitions\":[\"(.*?)]");
Matcher matcher2 = def.matcher(output);
event.getTextChannel().sendMessage(matcher2.toString());
if (matcher.find() && matcher2.find()) {
event.getTextChannel().sendMessage("Reading: "+matcher.group(1)).queue();
event.getTextChannel().sendMessage("Definition: "+matcher2.group(1)).queue();
}
else {
event.getTextChannel().sendMessage("Word not found").queue();
}
}
}
You had to escape the [ character to \\[ (once for the Java String and once for the Regex). You also did forget the closing \".
the correct pattern looks like this:
Pattern def = Pattern.compile("\"english_definitions\":\\[\"(.*?)\"]");
At the output, you might want to readd \" and start/end.
event.getTextChannel().sendMessage("Definition: \""+matcher2.group(1) + "\"").queue();
Hi, you can see my code below. I have some strings Country, rank and grank in my code, initially they will be null, but if regex is mached, it should change the value. But even if regex is matched it is not changing the value it is always null. If I remove all if statements and append the string it works fine, but if match is not found it is throwing an exception. Please let me know how can I check this in if logic.
System.err.println(content);
Pattern c = Pattern.compile("NAME=\"(.*)\" RANK");
Pattern r = Pattern.compile("\" RANK=\"(.*)\"");
Pattern gr = Pattern.compile("\" TEXT=\"(.*)\" SOURCE");
Matcher co = c.matcher(content);
Matcher ra = r.matcher(content);
Matcher gra = gr.matcher(content);
co.find();
ra.find();
gra.find();
String country = null;
String Rank = null;
String Grank = null;
if (co.matches()) {
country = co.group(1);
}
if (ra.matches()) {
Rank = ra.group(1);
}
if (gra.matches()) {
Grank = gra.group(1);
}
You have to escape a single \ - use double \\ then it should work.
Tried this?
while (co.find()) {
System.out.print("Start index: " + co.start());
System.out.print(" End index: " + co.end() + " ");
System.out.println(co.group());
}
Personally I can't make your program work with / without the if so it's not a problem of logic but just a problem that it doesn't match the string for me
So I changed it to get something working, maybe you can use it :)
String content = "NAME=\"salut\" RANK=\"pouet\" TEXT=\"text\" SOURCE";
System.out.println(content);
System.out.println(content.replaceAll(("NAME=\"(.*)\"\\sRANK=\"(.*)\"\\sTEXT=\"(.*)\" SOURCE"), "$1---$2---$3"));
Output
NAME="salut" RANK="pouet" TEXT="text" SOURCE
salut---pouet---text
How to get the part of data from string:
csvFile = "c:/Users//PHV/01Surname local.csv"
i need to extract Surname from above string
UPD
what you think about it?
File f = new File(csvFile);
String[] parts = f.getName().split(" ");
String strParts = new String(parts[0]);
String finFileName = strParts.substring(2, strParts.length());
You need a regular expression. Something like:
Pattern p = Pattern.compile("^.*/[0-9]+(a-zA-Z)+ .*");
Matcher m = p.matcher(csvFile);
String surname;
if (m.matches()) {
surname = m.group(1);
} else {
System.out.println("filename seems malformed: " + csvFile);
}
UPDATE: Here is a tutorial about regular expressions but not sure it is the best. I think it must work for you though: http://docs.oracle.com/javase/tutorial/essential/regex/
I'm not sure I understand your question, but I assume you want to extract "Surname". If that's correct, please try this:
String surname = csvFile.substring(csvFile.lastIndexOf("/") + 3, csvFile.lastIndexOf(" "));
Hi I've got a log file containing trace routes and pings.
Ive seperated these by using
if (scanner.nextLine ().startsWith ("64 bytes"){}
so I can work with just the pings for now.
All I'm interested in from the ping is time=XX
example data line =
64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms
I have been reading other peoples similar questions and I'm not sure how to apply to mine.
I literally need just the numbers as I will be putting them into a csv file so I can make a graph of the data.
edit: Using robins solution I'm now having my pings being spurted out on screen, except it's doing every other and missing the first.
while (scanner.hasNextLine ()) {
//take only pings.
if (scanner.nextLine ().startsWith ("64 bytes")){
String line = scanner.nextLine ();
String pingAsString = line.substring (line.lastIndexOf ("=") + 1, (line.length () - "ms".length ()));
Double ping = Double.valueOf (pingAsString);
System.out.println ("PING AS STRING = "+ping);
}
}
OK SORTED. THAT JUST NEEDED TO MOVE LINE ASSIGNMENT. CAPS. but made it clear. :D
Try using a RegularExpression to pull out the piece of data you need:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExTest {
public static void main(String[] args) {
String test = "line= 14103 64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms";
// build the regular expression string
String regex = ".*time=(\\d+).*";
// compile the regular expresion into a Pattern we can use on the test string
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(test);
// if the regular expression matches, grab the value matching the
// expression in the first set of parentheses: "(\d+)"
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
}
}
Or you can just use the available methods on String if you do not want to perform reg-ex magic
String line = ...
String pingAsString = line.substring( line.lastIndexOf("=")+1, (line.length() - " ms".length() ) );
Integer ping = Integer.valueOf( pingAsString );
Scanner scanner = new Scanner (new File ("./sample.log"));
while (scanner.hasNext ())
{
String line = scanner.nextLine ();
if (line.startsWith ("64 bytes")) {
String ms = line.replaceAll (".*time=([0-9]+) ms", "$1");
System.out.println ("ping = " + ms);
} // else System.out.println ("fail " + line);
}
Your problem is, that you call:
if (scanner.nextLine ().startsWith ("64 bytes")){
which means the line is grabbed, but not assigned to a variable. The result is immediately tested for startingWith, but then you call nextLine again, and get the next line, of course:
String line = scanner.nextLine ();
That is the second line.