哪个正则表达式会让我只匹配第一个和最后一个字母?

时间:2014-07-25 18:23:26

标签: c# regex

示例:

i General Biology i
i General Biology
General Biology i

我需要抓住任何以单个字母或数字开头,以字母或数字结尾,或者以单个字母或数字开头和结尾的短语,以便我可以预先解析数据:

General Biology

我在Rubular上尝试了很多例子,但似乎无法想出这一点。我已经使用文字匹配组来获取这些字符,但我不希望匹配组本身只是希望正则表达式只捕获这两个字母。

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法实现此目的:

String result = Regex.Replace(input, @"(?i)^[a-z0-9]\s+|\s+[a-z0-9]$", "");

<强>解释

这将删除字符串开头/结尾处的单个字母/数字,后跟或前面有空格。

 (?i)        #  set flags for this block (case-insensitive)
 ^           #  the beginning of the string
 [a-z0-9]    #  any character of: 'a' to 'z', '0' to '9'
 \s+         #  whitespace (\n, \r, \t, \f, and " ") (1 or more times)
|            # OR
 \s+         #  whitespace (\n, \r, \t, \f, and " ") (1 or more times)
 [a-z0-9]    #  any character of: 'a' to 'z', '0' to '9'
 $           #  before an optional \n, and the end of the string

Working Demo

相关问题