简体   繁体   中英

Regex to match first word in sentence

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, I would like to say \\"Hello!\\""

This doesn't work:

"""([A-Z].*?(?=^[A-Za-z]))""".r
(?:^|(?:[.!?]\s))(\w+)

Will match the first word in every sentence.

http://rubular.com/r/rJtPbvUEwx

[a-z]+

This should be enough as it will get the first az characters (assuming case-insensitive).

In case it doesn't work, you could try [az]+\\b , or even ^[az]\\b , but the last one assumes that the string starts with the word.

您可以使用以下正则表达式: ^[^\\s]+^[^ ]+

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.

You can use this regex: ^\\s*([a-zA-Z0-9]+) .

The first word can be found at a captured group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM