How to extract first 3 characters from an alphanumeric string in Java? For example- if the alphanumeric string is 12A12D3F34DFdHNB38HG. So I want to extract ADF
Asked
Active
Viewed 2,105 times
-5
-
2What about the code you use? Also, non accentuated Latin letters are not the only alphabetic characters... – fge Aug 03 '16 at 17:07
-
1[String.substring()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)) – jonhopkins Aug 03 '16 at 17:08
-
1Post your code. This regex should work fine. – Pshemo Aug 03 '16 at 17:15
-
Seeing as `String`s consist entirely of `char`acters, it's not clear what you mean by "*it only works if the string is starting with a character*". Please include what you've tried so far and a clear description of the problem you're running into. "It doesn't work" isn't something we can diagnose. – dimo414 Aug 03 '16 at 18:23
-
You may use Pattern.compile("[a-zA-Z]{3}") – JavaHopper Aug 03 '16 at 18:28
-
Possible duplicate of [up to first N characters](http://stackoverflow.com/questions/1583940/up-to-first-n-characters) – Inzimam Tariq IT Aug 03 '16 at 18:59
-
It can be done with an easy [`s.replaceAll("(?i)^[^a-z]*([a-z])[^a-z]*([a-z])[^a-z]*([a-z]).*$", "$1$2$3")`](https://regex101.com/r/uD5cO0/1). – Wiktor Stribiżew Aug 03 '16 at 20:15
-
Wiktor Stribizew- Thank you, its working – Garima Virmani Aug 05 '16 at 04:10
2 Answers
0
To extract the first three characters of a String, you can simply use the substring() method in the String class.
String firstThreeCharacters = str.substring(0, 3);
If this was not what you are asking for, please clarify your question since it is arguably ambiguous.
EDIT: @Wiktor Stribiżew has a good answer for your clarified question. I'm re-posting it here to make the answer more visible for other users.
String firstThreeCharacters = str.replaceAll("(?i)^[^a-z]*([a-z])[^a-z]*([a-z])[^a-z]*([a-z]).*$", "$1$2$3")

Micah Stairs
- 235
- 2
- 11
-
actually i have a alphanumeric string. For eg-A12D3F376HF7H23H87JH. So I want to extract first three alphabets so i want the output to be ADF – Garima Virmani Aug 05 '16 at 04:04
0
You need pattern as : [a-zA-z0-9]{3}

Shekhar Khairnar
- 2,643
- 3
- 26
- 44
-
no this pattern extracts first three characters,be it number or be it alphabet. I want to extract only alphabets – Garima Virmani Aug 05 '16 at 03:59