Do you have any ideas how could I get first character after second dot of the string.
String str1 = "test.1231.asdasd.cccc.2.a.2";
String str2 = "aaa.1.22224.sadsada";
In first case I should get a
and in second 2
.
I thought about dividing string with dot, and extracting first character of third element. But it seems to complicated and I think there is better way.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
How about a regex for this?
Pattern p = Pattern.compile(".+?\\..+?\\.(\\w)");
Matcher m = p.matcher(str1);
if (m.find()) {
System.out.println(m.group(1));
}
The regex says: find anything one or more times in a non-greedy fashion (.+?
), that must be followed by a dot (\\.
), than again anything one or more times in a non-greedy fashion (.+?
) followed by a dot (\\.
). After this was matched take the first word character in the first group ((\\w)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With