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



示例:

i General Biology i
i General Biology
General Biology i

我需要捕捉任何以单个字母或数字开头、以字母或数字结尾、或两者都以单个字母和数字开头和结尾的短语,以便我可以将数据预解析为:

General Biology

我在Rubular上试过很多例子,但似乎都想不通。我使用了文字匹配组来获取这些字符,但我不想要匹配组本身,我只希望正则表达式只捕获这两个字母。

您可以使用以下方法来实现这一点:

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

工作演示

相关内容

最新更新