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.

Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- 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 }

浙公网安备 33010602011771号