regex - How can I read this string in Java? -
i have string such this: "xxxxxxx , yyyyyyy - zzzzzz" , happens "xxxxxxx - zzzzzz" length of x may vary. want get, x word. there easy way this?
what thought was: iterate through string, append stringbuilder every char read until read ",", break iteration , word, looks pretty messy.
so maybe there easier way this.
here several ways 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 1 more :)
update:
to find first word, may use following regex pattern:
string pattern = "[\\s\\p{p}]+";
\s
stands whitespace, , \p{p}
stands punctuation.
you can use split
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 output xxxxxxx
. however, if need restrict punctuation smaller subset, either exclude them in &&[^-]
negated subtraction:
[\\s\\p{p}&&[^-]]+
or define own range:
[\\s.,;:]+
just another demo
Comments
Post a Comment