Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first character after second dot java

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.

like image 867
Suule Avatar asked Aug 24 '18 11:08

Suule


People also ask

How do you find the first occurrence of a character in a string in Java?

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.

How do you find the first character in string1?

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 .


1 Answers

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)).

like image 178
Eugene Avatar answered Sep 28 '22 14:09

Eugene