This SHOULD be simple for some reason I seem to be stretching the boundaries of my regex knowledge. I simply need a regex that will match the first letter in a word. I only want letters from an array that start with x
y
or z
. This seems to reduce the amount of items in the array... but I'm not sure why since the results aren't what I'm expecting.
Regex regex = new Regex(@"\b[x|y|z]");
string[] array = text.Where(x => regex.IsMatch(x)).ToArray()); // 'text' is an array
Try
\b([xyz]\w*)
\\w*
means zero to many word characters. When using []
the |
is implied between the characters. So, [xyz]
means x, y, or z. Then placing the ()
captures the word. So, in short we find something that is the start of a word then capture a string of word characters starting with x, y, or z.
Also, you can change \\w
with [A-Za-z]
since some will include _
and numbers as a word character:)
Can also go here to test regex. Even though it is for php , python , and javascript it still is nice to test:)
Hope this helps some!
这可能是你在搜索的内容:
Regex regex = new Regex(@"^(x|y|z).+$");
我试过这个,它似乎做你需要的:
new Regex(@"\b[x|y|z](?=\w*\b)")
If i understood your answer right, then you want to match words that start with any of the letters x
, y
or z
. The answer you accepted would match everything after the occurence of x
or y
or z
.
try this instead:
[xyz]\w+
in a text like
lalalalla nananna x xaa yaaa zaaa lalala
it would match the three words
xaa
yaaa
zaaa
individually.
if you also want to match single occurences of the letters, use
[xyz]\w*
instead, which would match
x
xaa
yaaa
zaaa
.
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.