Here are several ways to get the first character:
String str = "x , y - zzzzzz";
System.out.println(str.charAt(0));
System.out.println(str.substring(0, 1));
System.out.println(str.replaceAll("^(.).*", "$1"));
See IDEONE demo
Choose the one you like more 🙂
UPDATE:
To find the first word, you may use the following regex pattern:
String pattern = "[\\s\\p{P}]+";
\s
stands for whitespace, and \p{P}
stands for punctuation.
You can use split
with this as in
String str = "xxxxxxx , yyyyyyy - zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx - zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx, zzzzzz";
System.out.println(str.split(pattern)[0]);
str = "xxxxxxx-zzzzzz";
System.out.println(str.split(pattern)[0]);
All will output xxxxxxx
. However, if you need to restrict the punctuation to some smaller subset, either exclude them in the &&[^-]
negated subtraction:
[\\s\\p{P}&&[^-]]+
Or just define your own range:
[\\s.,;:]+
Just another demo
4
solved How can I read this string in Java? [closed]