Reputation: 15
I'm looking for a regular expression to match the beginning of specific words throughout a string. Say I have this:
This is the example string of text.
I would be looking to match each T that starts a word:
This is the example string of text.
Any help would be much appreciated.
Upvotes: 0
Views: 346
Reputation: 26
I believe that the \b
metacharacter limits a regular expression to "word boundaries", meaning it will let you match "whole words only". By using \b
at the beginning of your regular expression you can match whatever you want, as long as it starts a word.
In your example:
\b[tT]
Similarly, if you'd wish to match the letter T at the end of words you would just place the \b at the end of the regular expression.
Upvotes: 1
Reputation: 151244
trying in irb (Ruby):
irb(main):001:0> "This is the example string of text.".scan(/\bt\w+/i)
=> ["This", "the", "text"]
for /\bt\w+/i
, \b
is the boundary, t
is the character t
that you want to start with, and \w+
is alphanumeric or underscore, with 1 or more occurrences. The i
is ignore case.
If you want only alphabets and want to match just a t
as well, then you can use
irb(main):002:0> "This is the example string of text.".scan(/\bt[a-z]*/i)
=> ["This", "the", "text"]
The [a-z]
means the class of characters from a
to z
. *
means 0 or more occurrences.
Upvotes: 1