I would like to get the sub-string after the term "[ DevStatusReq ] =" in the following content
"10-01-2018 10:24:08.006 : |=> [ DevStatusReq ] = 0x06".I want to use regex.
Here is my code :
String margin = LogExtract.extractDataInFile(path, "Margin", "Margin = (.*?) dB");
String devStatusReq = LogExtract.extractDataInFile(path, "DevStatusReq", "[ DevStatusReq ] = (.*) ");
System.out.println("Margin : " + margin + " | DevStatusReq : " + devStatusReq );
My method which return the result found is here :
public static String extractDataInFile(String filePath,String element, String filter) {
String result = element + "has not been found ";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if(line.contains(element)) {
element = line;
Pattern pattern = Pattern.compile(filter);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
result= matcher.group(1);
}
}
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The console displays :
Margin : 39 | DevStatusReq : DevStatusReqhas not been found
My regex in the second call of the method is wrong. Can you help me please ?
Thank you!
In regular expressions [] are special characters to build a set of values :
so [ DevStatusReq ] means one of the following letter DSR evtausq
The right pattern for you is \[ DevStatusReq \] = (.*)
In Java \ is a special character, so you need to escape it and your pattern in the code will be :
LogExtract.extractDataInFile(path, "DevStatusReq", "\\[ DevStatusReq \\] = (.*) ");
Related
I am trying to separate these value into ID, FullName and Phone. I know we can split it by using java split function. But is there any other ways to separate it? Values:
1 Peater John 2522523254
10 Neal Tom 2522523254
11 Tom Jackson 2522523254
111 Jack Smith 2522523254
12 Brownson Black 2522523254
I tried to use substring method but it won't work properly.
String id = line.substring(0, 3);
If I do this then it will work till 4th line, but other won't work properly.
If it is fixed length you can use String.substring(). But you should also trim() the result before you try to convert it to numeric:
String idTxt=line.substring(0,4);
Long id=Long.parseLong(idTxt.trim());
String name=line.substring(5,25).trim(); // or whatever the size is of name column.
You can use regex and Pattern
Pattern pattern = Pattern.compile("(\\d*)\s*([\\w\\s]*)\\s*(\\d*)");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
string id = matcher.group(0);
string name = matcher.group(1);
string phone = matcher.group(2);
}
package Generic;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main
{
public static void main(String[] args)
{
String txt=" 12 Brownson Black 2522523254";
String re1=".*?"; // Non-greedy match on filler
String re2="(\\d+)"; // Integer Number 1
String re3="(\\s+)"; // White Space 1
String re4="((?:[a-z][a-z]+))"; // Word 1
String re5="(\\s+)"; // White Space 2
String re6="((?:[a-z][a-z]+))"; // Word 2
String re7="(\\s+)"; // White Space 3
String re8="(\\d+)"; // Integer Number 2
Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find())
{
int id = Integer.parseInt(m.group(1));
String name =m.group(3) + " ";
name = name+m.group(5);
long phone = Long.parseLong(m.group(7));
System.out.println(id);
System.out.println(name);
System.out.println(phone);
}
}
}
What about this:
int first_space;
int last_space;
first_space = my_string.indexOf(' ');
last_space = my_string.lastIndexOf(' ');
if ((first_space > 0) && (last_space > first_space))
{
long id;
String full_name;
String phone;
id = Long.parseLong(my_string.substring(0, first_space));
full_name = my_string.substring(first_space + 1, last_space);
phone = my_string.substring(last_space + 1);
}
Use a regexp:
private static final Pattern RE = Pattern.compile(
"^\\s*(\\d+)\\s+(\\S+(?: \\S+)*)\\s+(\\d+)\\s*$");
Matcher matcher = RE.matcher(s);
if (matcher.matches()) {
System.out.println("ID: " + matcher.group(1));
System.out.println("FullName: " + matcher.group(2));
System.out.println("Phone: " + matcher.group(3));
}
You can use a StringTokenizer for this. You won't have to worry about amount of spaces and/or tabs before or after your values, and no need for complex regex expressions:
String line = " 1 Peater John\t2522523254 ";
StringTokenizer st = new StringTokenizer(line, " \t");
String id = "";
String name = "";
String phone = "";
// The first token is your id, you can parse it to an int if you like or need it
if(st.hasMoreTokens()) {
id = st.nextToken();
}
// Loop over the remaining tokens
while(st.hasMoreTokens()) {
String token = st.nextToken();
// As long a there are other tokens, you're processing the name
if(st.hasMoreTokens()) {
if(name.length() > 0) {
name = name + " ";
}
name = name + token;
}
// If there are no more tokens, you've reached the phone number
else {
phone = token;
}
}
System.out.println(id);
System.out.println(name);
System.out.println(phone);
I want to find and count all the occurrences of the words unit, device, method, module in every line of the text file separately. That's what I've done, but I don't know how to use multiple patterns and how to count the occurrence of every word in the line separately? Now it counts only occurrences of all words together for every line. Thank you in advance!
private void countPaterns() throws IOException {
Pattern nom = Pattern.compile("unit|device|method|module|material|process|system");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
int countnomen = 0;
while (matcher.find()) {
countnomen++;
}
//intList.add(countnomen);
System.out.println(countnomen + " davon ist das Wort System");
}
r.close();
//return intList;
}
Better to use a word boundary and use a map to keep counts of each matched keyword.
Pattern nom = Pattern.compile("\\b(unit|device|method|module|material|process|system)\\b");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
Map<String, Integer> counts = new HashMap<>();
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
while (matcher.find()) {
String key = matcher.group(1);
int c = 0;
if (counts.containsKey(key))
c = counts.get(key);
counts.put(key, c+1)
}
}
r.close();
System.out.println(counts);
Here's a Java 9 (and above) solution:
public static void main(String[] args) {
List<String> expressions = List.of("(good)", "(bad)");
String phrase = " good bad bad good good bad bad bad";
for (String regex : expressions) {
Pattern gPattern = Pattern.compile(regex);
Matcher matcher = gPattern.matcher(phrase);
long count = matcher.results().count();
System.out.println("Pattern \"" + regex + "\" appears " + count + (count == 1 ? " time" : " times"));
}
}
Outputs
Pattern "(good)" appears 3 times
Pattern "(bad)" appears 5 times
My Java code:
String subjectString = "BYWW4 AterMux TP 46[_221] \n"
+ "FHTTY TC AterMux TP 9 \n"
+ "TUI_OO AterMux TP 2[_225] \n"
+ "F-UYRE TC AterMux TP 2 \n"
+ "RRRDSA AterMux TP 31[_256] ";
String textStr[] = subjectString.split("\n");
for (int i = 0; i < textStr.length; i++) {
String ResultString = null;
try {
Pattern regex = Pattern.compile("????????");
Matcher regexMatcher = regex.matcher(textStr[i]);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
System.out.println(ResultString); ///
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
}
I want the program to print the value after word (TP) and before ([) on this code to get result like below:4692231
You can use regexp TP\s*(\d+)\[ (double backslashes in Java code) and get a value with regexMatcher.group(1).
But you should not recreate it on each iteration of the loop, you should use Pattern.compile once per regexp.
I am reading a file and trying to modify it in the following order:
if line is empty trim()
if line ends with \ strip that char and add next line to it.
The complete line contains double quotes and there are white spaces between the quotes, replace the white space with ~.
For example: "This is text within double quotes"
change to : "This~is~text~within~double~quotes"
This code is working but buggy.
Here is the issue when it finds a line that ends with \ and others that done.
for example:
line 1 and \
line 2
line 3
so Instead of having
line 1 and line 2
line 3
I have this:
line 1 and line 2 line 3
Coded updated:
public List<String> OpenFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
//StringBuilder concatenatedLine = new StringBuilder();
List<String> formattedStrings = new ArrayList<>();
//Pattern matcher = Pattern.compile("\"([^\"]+)\"");
while ((line = br.readLine()) != null) {
boolean addToPreviousLine;
if (line.isEmpty()) {
line.trim();
}
if (line.contains("\"")) {
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
String match = matcher.group();
line = line.replace(match, match.replaceAll("\\s+", "~"));
}
}
if (line.endsWith("\\")) {
addToPreviousLine = false;
line = line.substring(0, line.length() - 1);
formattedStrings.add(line);
} else {
addToPreviousLine = true;
}
if (addToPreviousLine) {
int previousLineIndex = formattedStrings.size() - 1;
if (previousLineIndex > -1) {
// Combine the previous line and current line
String previousLine = formattedStrings.remove(previousLineIndex);
line = previousLine + " " + line;
formattedStrings.add(line);
}
}
testScan(formattedStrings);
//concatenatedLine.setLength(0);
}
return formattedStrings;
}
Update
I'm giving you what you need, without trying to write all the code for you. You just need to figure out where to place these snippets.
If line is empty trim()
if (line.matches("\\s+")) {
line = "";
// I don't think you want to add an empty line to your return result. If you do, just omit the continue;
continue;
}
If line contains double quotes and white spaces in them, replace the white space with ~. For example: "This is text within double quotes" change to : "This~is~text~within~double~quotes"
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
String match = matcher.group();
line = line.replace(match, match.replaceAll("\\s+", "~"));
}
If line ends with \ strip that char and add the next line. You need to have flag to track when to do this.
if (line.endsWith("\\")) {
addToPreviousLine = true;
line = line.substring(0, line.length() - 1);
} else {
addToPreviousLine = false;
}
Now, to add the next line to the previous line you'll need something like (Figure out where to place this snippet):
if (addToPreviousLine) {
int previousLineIndex = formattedStrings.size() - 1;
if (previousLineIndex > -1) {
// Combine the previous line and current line
String previousLine = formattedStrings.remove(previousLineIndex);
line = previousLine + " " + line;
}
}
You still do not need the StringBuffer or StringBuilder. Just modify the current line and add the current line to your formattedStrings List.
I'm not very good with regex, so here's a programmatic method to do it:
String string = "He said, \"Hello Mr Nice Guy\"";
// split it along the quotes
String splitString[] = string.split("\"");
// loop through, each odd indexted item is inside quotations
for(int i = 0; i < splitString.length; i++) {
if(i % 2 > 0) {
splitString[i] = splitString[i].replaceAll(" ", "~");
}
}
String finalString = "";
// re-build the string w/ quotes added back in
for(int i = 0; i < splitString.length; i++) {
if(i % 2 > 0) {
finalString += "\"" + splitString[i] + "\"";
} else {
finalString += splitString[i];
}
}
System.out.println(finalString);
Output: He said, "Hello~Mr~Nice~Guy"
Step 3:
String text;
text = text.replaceAll("\\s", "~");
If you want to replace spaces occur within double quotes with ~s,
if (line.contains("\"")) {
String line = "\"This is a line with spaces\"";
String result = "";
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(line);
while (m.find()) {
result = m.group(1).replace(" ", "~");
}
}
instead of
if (line.contains("\"")) {
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(line);
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group().replaceAll("\\s+", ""));
}
I would do this
if (line.matches(("\"([^\"]+)\"")) {
line= line.replaceAll("\\s+", ""));
}
How can I add this to what I have above ?
concatenatedLine.append(line);
String fullLine = concatenatedLine.toString();
if (fullLine.contains("\"")) {
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\"([^\"]+)\"").matcher(fullLine);
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group().replaceAll("\\s+", ""));
formattedStrings.add(sb.toString());
}else
formattedStrings.add(fullLine);
I would like to use regex to parse a message received through a socket in an Android Client and put part of the message in a list.
This is the message to parse:
{Code=1;NumServices=3;Service1=World Weather Online;Link1=http://www.worldweatheronline.com/;Service2=Open Weather Map;Link2=http://openweathermap.org/;Service3=Weather;Link3=http://www.weather.gov/;}
and the method I'm using:
private void parse(String mess) {
String Code="0";
Pattern pattern = Pattern.compile("Code=(.*?);");
Matcher matcher = pattern.matcher(mess);
while (matcher.find()) {
Code = matcher.group(1);
Log.d("Matcher", "PATTERN MATCHES! Code parsed "+Code );
// System.out.println("Code: "+Code);
}
Log.d("Matcher", "PATTERN MATCHES! Code not parsed "+Code );
if(Code.compareTo("1")==0){
// System.out.println("testing the parser");
// Pattern pattern1 = Pattern.compile(";CPU=(.*?);Screen");
Pattern pattern2 = Pattern.compile("NumServices=(.*?);");
Matcher matcher2 = pattern2.matcher(mess);
int number=0;
if (matcher2.find()) {
String numb = matcher2.group(1);
this.tester = numb;
Log.d("Matcher", "PATTERN MATCHES! numb services");
number = Integer.parseInt(numb);
}
else{
this.tester = "NOT FOUND";
Log.d("Matcher", "PATTERN MATCHES! match num failed");
}
int i;
for(i=1;i<=number;i++){
Pattern pattern3 = Pattern.compile(";Service"+i+"=(.*?);");
Pattern pattern4 = Pattern.compile(";Link"+i+"=(.*?);");
Matcher matcher3 = pattern3.matcher(mess);
Matcher matcher4 = pattern4.matcher(mess);
if (matcher3.find()) {
// Log.d("Matcher", "PATTERN MATCHES! services");
String serv = matcher3.group(1);
// this.tester = serv;
your_array_list.add(serv);
}
if (matcher4.find()) {
Log.d("Matcher", "PATTERN MATCHES! links");
String link = matcher4.group(1);
your_array_list2.add(link);
}
}
}
}
None of the log.d works so I cannot verify the flow of the code. What's weird is that I tested the same code in Eclipse and it works. When I use toast to display, it gives me the value of Code, but not of Service. Is there an error somewhere or does regex work differently in Android?
Thanks.
You can actually use 1 regex to capture all pertinent data:
Code=([^;]*);NumServices=([^;]*);|Service(\d+)=([^;]*);Link\d+=([^;]*);
Here is a sample code:
String str = "{Code=1;NumServices=3;Service1=World Weather Online;Link1=http://www.worldweatheronline.com/;Service2=Open Weather Map;Link2=http://openweathermap.org/;Service3=Weather;Link3=http://www.weather.gov/;}";
Pattern ptrn = Pattern.compile("Code=([^;]*);NumServices=([^;]*);|Service(\\d+)=([^;]*);Link\\d+=([^;]*);");
Matcher matcher = ptrn.matcher(str);
while (matcher.find()) {
if (matcher.group(1) != null) {
System.out.println("Code: " + matcher.group(1));
System.out.println("NumServices: " + matcher.group(2));
}
else if (matcher.group(1) == null && matcher.group(2) == null) {
System.out.println("Service #: " + matcher.group(3));
System.out.println("Service Name: " + matcher.group(4));
System.out.println("Link: " + matcher.group(5));
}
}
See IDEONE demo