What is the best way to extract the first word from a string in Java?

后端 未结 13 2083
小蘑菇
小蘑菇 2020-11-29 02:38

Trying to write a short method so that I can parse a string and extract the first word. I have been looking for the best way to do this.

I assume I would use s

13条回答
  •  失恋的感觉
    2020-11-29 03:22

    None of these answers appears to define what the OP might mean by a "word". As others have already said, a "word boundary" may be a comma, and certainly can't be counted on to be a space, or even "white space" (i.e. also tabs, newlines, etc.)

    At the simplest, I'd say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It's a big topic.

    But a start might be this (NB written in Groovy):

    String givenString = "one two9 thr0ee four"
    // String givenString = "oňňÜÐæne;:tŵo9===tĥr0eè? four!"
    // String givenString = "mouse"
    // String givenString = "&&^^^%"
    
    String[] substrings = givenString.split( '[^\\p{L}^\\d]+' )
    
    println "substrings |$substrings|"
    
    println "first word |${substrings[0]}|"
    

    This works OK for the first, second and third givenStrings. For "&&^^^%" it says that the first "word" is a zero-length string, and the second is "^^^". Actually a leading zero-length token is String.split's way of saying "your given String starts not with a token but a delimiter".

    NB in regex \p{L} means "any Unicode letter". The parameter of String.split is of course what defines the "delimiter pattern"... i.e. a clump of characters which separates tokens.

    NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.

    NB3 My first port of call was Apache Commons' StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out... https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html ... although something of use may be lurking there.

提交回复
热议问题