C#正则的括号问题

在LeetCode上刷题

500. Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

 

American keyboard

 

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

 

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

 

看到一个java的正则解法:

1 public String[] findWords(String[] words) {
2     return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);
3 }

自己用C#写时候不正确:

1 public string[] FindWords(string[] words) {
2         return words.Where(w=>new System.Text.RegularExpressions.Regex("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*",
3             System.Text.RegularExpressions.RegexOptions.IgnoreCase).IsMatch(w)).ToArray();
4     }

经过一段时间的查找资料,修改成下面这样通过了:

1 public string[] FindWords(string[] words) {
2         return words.Where(w=>new System.Text.RegularExpressions.Regex("^([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$",
3             System.Text.RegularExpressions.RegexOptions.IgnoreCase).IsMatch(w)).ToArray();
4     }

 

posted @ 2017-06-29 02:35  笨人只能拼命  阅读(371)  评论(1)    收藏  举报