Regex to match first word in sentence

前端 未结 5 1298
花落未央
花落未央 2021-02-06 01:49

I am looking for a regex that matches first word in a sentence excluding punctuation and white space. For example: \"This\" in \"This is a sentence.\" and \"First\" in \"First,

5条回答
  •  耶瑟儿~
    2021-02-06 02:32

    This is an old thread but people might need this like I did. None of the above works if your sentence starts with one or more spaces. I did this to get the first (non empty) word in the sentence :

    (?<=^[\s"']*)(\w+)
    

    Explanation:

    (?<=^[\s"']*) positive lookbehind in order to look for the start of the string, followed by zero or more spaces or punctuation characters (you can add more between the brackets), but do not include it in the match.
    (\w+) the actual match of the word, which will be returned

    The following words in the sentence are not matched as they do not satisfy the lookbehind.

提交回复
热议问题