Regex to match first word in sentence

百般思念 提交于 2019-12-03 12:45:14

问题


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

回答1:


(?:^|(?:[.!?]\s))(\w+)

Will match the first word in every sentence.

http://rubular.com/r/rJtPbvUEwx




回答2:


[a-z]+

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

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




回答3:


You can use this regex: ^[^\s]+ or ^[^ ]+.




回答4:


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.




回答5:


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

The first word can be found at a captured group.



来源:https://stackoverflow.com/questions/14767080/regex-to-match-first-word-in-sentence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!