正则表达式匹配以特定单词开头的字符串 [英] Regular Expression to match string starting with a specific word
问题描述
如何创建正则表达式以匹配字符串开头的单词.我们希望在字符串的开头匹配 stop
并且后面的任何内容都可以.
How do I create a regular expression to match a word at the beginning of a string. We are looking to match stop
at the beginning of a string and anything can follow it.
例如表达式应该匹配:
stop
stop random
stopping
谢谢.
推荐答案
如果你只想匹配以 stop 开头的行
If you wish to match only lines beginning with stop use
^stop
如果你想匹配以单词 stop 开头的行,后跟一个空格
If you wish to match lines beginning with the word stop followed by a space
^stop\s
或者,如果您希望匹配以单词 stop 开头但后跟空格或任何其他可以使用的非单词字符的行(您的正则表达式允许)
Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)
^stop\W
另一方面,接下来的内容在大多数正则表达式风格中匹配字符串开头的单词(在这些风格中 \w 与 \W 匹配)
On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)
^\w
如果你的口味没有 \w 快捷方式,你可以使用
If your flavor does not have the \w shortcut, you can use
^[a-zA-Z0-9]+
请注意,第二个习语只会匹配字母和数字,而不会匹配任何符号.
Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.
查看您的正则表达式风格手册,了解允许使用哪些快捷方式以及它们究竟匹配什么(以及它们如何处理 Unicode.)
Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)
这篇关于正则表达式匹配以特定单词开头的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!