Read specific line out of String - java

I have a String that looks like this:
String meta = "1 \n"
+ "Herst \n"
+ "01 Jan 2019 – 31 Dec 2020 \n"
+ "01 Jan 2020 \n"
+ "CONFIG \n"
+ "XML \n"
+ "AES \n"
+ "RSA \n"
+ "256 \n"
+ "16 \n"
+ "128 \n";
What is the smartest way if I want to read a specific line out of this String in Java?
For example, I need in another part of my code the number of the second last line (in this case it's 16). How can I read this number out of the String?

If it's already in String form, just split it into lines using \n as a delimiter to get an array of lines:
String[] lines = meta.split("\n");
Then you can easily get a specific line. For instance, System.out.println(lines[9]) will print 16.
If you need the 16 in the form of an int, you'd need to remove the whitespaces around it, and parse it:
int parsed = Integer.parseInt(lines[9].trim());

Related

Android toLowerCase() issue with accented characters

My app has a feature to filter content based on some keywords.
This is case insensitive so in order to work I first call String.toLowerCase() on the source content.
The issue I have is when the source is in upper case and contains accentuated characters like with the french word: "INVITÉ"
This word when set to lowercase using the device default locale returns "invité"
The problem is that the last character is not the same as the lowercase character "é"
Instead it's the combination of 2 chars:
"e" 101 &
" ' " 769
Because of this "invité" does not match "invité"
How can I solve this? I would prefer not to remove accentuated characters altogether
You should normalize the string like this.
String upper = "INVITÉ";
System.out.println(upper + " length=" + upper.length());
String lower = upper.toLowerCase();
System.out.println(lower + " length=" + lower.length());
String normalized = Normalizer.normalize(lower, Normalizer.Form.NFC);
System.out.println(normalized + " length=" + normalized.length());
output:
INVITÉ length=7
invité length=7
invité length=6
It also works for Japanese.
String japanese = "が";
System.out.println(japanese + " length=" + japanese.length());
String normalized = Normalizer.normalize(japanese, Normalizer.Form.NFC);
System.out.println(normalized + " length=" + normalized.length());
output:
が length=2
が length=1

How to Insert slashes into a string?

I have a birth date number in the format: 890520, so yy/mm/dd.
However, I need to display it separated by slashes, eg. 89/05/20
How can I do this, as there is no delimiter with which I can split the string?
String a = "890520";
System.out.println(a.substring(0, 2) + "/" + a.substring(2, 4) + "/" + a.substring(4));
substring() is what you are looking for.

Regex match till the end of text in Java

I want to fetch all the email addresses of From field using regex like get all lines of text that starts with "From:" and end with "/n" new line.
Here is the complete text on which I want to apply this regex,
Sent: Tue Mar 05 15:42:11 IST 2019
From: xtest#xyz.co.in
To: akm#xyz.com
Subject: Re: Foausrnisfseur invadlide (030000000000:3143)
Message:
----------------------------
Sent: Tue Mar 05 15:40:51 IST 2019
From: ytest#xyz.com
To: bpcla#xpanxion.com
Subject: Foausrnisfseur invadlide (O4562000888885456:3143)
Message:
This is not right please correct
Termes de paiement Foausrnisfseur non spécifiés
impact potentiel: 3 000,00
You should write From field with abc#xyz.com
and not From: field with abc#xyz.com in the column
Date détecté: 2019-02-26 12:55:03
---- Please do not delete or modify this line. (2423000000000149:3143) ----
-------------------------
Sent: Tue Mar 05 15:40:51 IST 2019
From: ytest#xyz.co.in
To: bpcla#xpanxion.com
Subject: Foausrnisfseur invadlide (O4562000888885456:3143)
I have tried following patterns but it did not work,
[^.?!]*(?<=[.?\s!])string(?:(?=[\s.?!])[^.?!]*(?:[.?!].*)?)?$
/^([\w\s\.]*)string([\w\s\.]*)$/
"^\\w*\\s*((?m)Name.*$)"
The desired result expected from above text is :
xtest#xyz.co.in,
ytest#xyz.com,
ytest#xyz.co.in,
PS. I want regex for Java logic
Try this pattern: ^From:\s*(\S+)$
It first matches beginning of a line with ^, then matches From: literally, then matches 0 or more whitespaces with \s*, then matches one or more non-whitespeaces and stores it in capturing group, $ matches end of a line.
To get e-mail address, just use value of first capturing group.
Demo
String test = " Sent: Tue Mar 05 15:42:11 IST 2019 "
+ " From: xtest#xyz.co.in "
+ " To: akm#xyz.com "
+ " Subject: Re: Foausrnisfseur invadlide (030000000000:3143) "
+ " Message: "
+ " "
+ " "
+ " ---------------------------- "
+ " "
+ " Sent: Tue Mar 05 15:40:51 IST 2019 "
+ " From: ytest#xyz.com "
+ " To: bpcla#xpanxion.com "
+ " Subject: Foausrnisfseur invadlide (O4562000888885456:3143) "
+ " Message: "
+ " This is not right please correct "
+ " Termes de paiement Foausrnisfseur non spécifiés "
+ " impact potentiel: 3 000,00 "
+ " You should write From field with abc#xyz.com "
+ " and not From: field with abc#xyz.com in the column "
+ " Date détecté: 2019-02-26 12:55:03 "
+ " "
+ " "
+ " ---- Please do not delete or modify this line. (2423000000000149:3143) ---- "
+ " " + " ------------------------- "
+ " Sent: Tue Mar 05 15:40:51 IST 2019 " + " From: ytest#xyz.co.in "
+ " To: bpcla#xpanxion.com "
+ " Subject: Foausrnisfseur invadlide (O4562000888885456:3143) ";
String emailRegex = "[a-zA-Z0-9._%+-]+#[A-Za-z0-9.-]+\\.[a-zA-Z]{2,6}";
Pattern pattern = Pattern.compile("From\\:\\s(" + emailRegex + ")");// From\\:\\s same as Form : and () here i added Email Id regex or you also change to (.*\n) but not recommended
Matcher match = pattern.matcher(test);
while (match.find()) {
System.out.println(match.group(1));
}
output :
xtest#xyz.co.in
ytest#xyz.com
ytest#xyz.co.in
Use this regular expression for your case:
From:\s+([\w-]+#([\w-]+\.)+[\w-]+)
I have tried this regular expression with https://www.freeformatter.com/java-regex-tester.html#ad-output and it is matching what you require.
Your required match is in capture Group 1.
Working Demo: https://regex101.com/r/dGaPbD/4
String emailRegex = "[^\\s]+"; // Replace with a better one
Matcher m = Pattern.compile("(?m)^From:\\s*(" + emailRegex + ")\\s*$").matcher(yourString);
List<String> allMatches = new ArrayList<String>();
while(m.find())
System.out.println(m.group(1));

What Regular Expression Will Get Last Price Listed On Receipt?

I have the following expression:
(?!\d+\s+TOTAL\s+)\$+\d+\.?\d+\s+
It produces the result "$23.00$0.03$23.80" from the following text:
SPEEDWAY 3007906
Wallace NC 28466
TRAM: 1086244
9/17/2017 2:12 pm
Pump 08
Regular Unleaded
8,716 # $2,639/6131
GAS TOTAL $23.00
TAX $0.03
TOTAL $23.80
Uisa
What regular expression will pull just $23.80 in this case? If I add positive lookahead, so that the expression is "(?!\d+\s+TOTAL\s+)\$+\d+\.?\d+\s+(?=.*\$\d+\.?\d+)", the result is "$23.00$0.03" and not "$23.80".
Please help. Thanks in advance.
Try this:
(?<=^TOTAL)\s*(\$\s*\d+\.?\d*)\s*$
Make sure you use MULTILINE match.
This will match all the spaces around the value, so you may want to strip those out to get the value
Example:
String in = "SPEEDWAY 3007906\n" +
"Wallace NC 28466 \n" +
"TRAM: 1086244 \n" +
"9/17/2017 2:12 pm \n" +
"Pump 08 \n" +
"Regular Unleaded \n" +
"8,716 # $2,639/6131 \n" +
"GAS TOTAL $23.00\n" +
"TAX $0.03 \n" +
"TOTAL $23.80\n" +
"Uisa ";
Pattern p = Pattern.compile("(?<=^TOTAL)\\s*(\\$\\s*\\d+\\.?\\d*)\\s*$", MULTILINE);
Matcher m = p.matcher(in);
if(m.find()) {
System.out.println(m.group(1));
}
This should print just the matched value
Maybe you could use a negative lookbehind to assert that what is before TOTAL is not GAS and capture your value in group 1.
(?<!GAS )TOTAL\s*(\$\d+\.\d+)
Demo output Java

writing a specific string to a file with Java

my codes dont seem to properly address what i intend to achieve.
a long string instead of a well broken and seperated string
it does not handle the 'seperator' appropriately ( produces , instead of ",")
also the 'optional' ( produces ' instead of " '")
Current result:
LOAD DATA INFILE 'max.csv'BADFILE 'max.bad'DISCARDFILE
'max.dis' APPEND INTO TABLEADDRESSfields terminated by,optionally enclosed
by'(ID,Name,sex)
the intended result should look like this
is there a better way of doing this or improving the above codes
Yeah. Use the character \n to start a new line in the file, and escape " characters as \". Also, you'll want to add a space after each variable.
content = " LOAD DATA\nINFILE "+ fileName + " BADFILE "+ badName + " DISCARDFILE " +
discardName + "\n\nAPPEND\nINTO TABLE "+ table + "\n fields terminated by \"" + separator
+ "\" optionally enclosed by '" + optional + "'\n (" + column + ")";
This is assuming fileName, badName, and discardName include the quotes around the names.
Don't reinvent the wheel... the apache commons-io library does all that in one line:
FileUtils.write(new File(controlName), content);
Here's the javadoc for FileUtils.write(File, CharSequence):
Writes a CharSequence to a file creating the file if it does not exist
To insert a new line you need to use \n or \r\n for windows
for example
discardName + "\n" //New line here
"APPEND INTO TABLE"
For the double quote symbol on the other hand you need to specifically type \" around the comma:
"fields terminated by \"" + separator +"\""
which will produce this ","
and that is similar to what the optional variable needs to be

Categories

Resources