【发布时间】:2021-01-07 18:29:50
【问题描述】:
我正在使用 C# 的 MongoDB 驱动程序,我正在查询从集合中获取与字段匹配的项目列表。
我正在使用带有以下表达式的 BsonRegularExpression 对象:
"/.*" + summonerName + "/"
这相当于 Sql 中的 LIKE,但是当我希望它不区分大小写时问题就来了。 为此,许多网站评论说它必须是这样的:
BsonRegularExpression expReg = new BsonRegularExpression("/.*" + summonerName + "/", "i");
当我在表达式后面加上这样的选项参数:“i”时,它不会返回任何东西。
我把整个代码留在这里:
public static List<Summoner> GetSummonerByName(String summonerName)
{
try
{
var database = dbClient.GetDatabase(databaseName);
var collection = database.GetCollection<Summoner>(collectionSummoner);
String nombreRegex = "";
var nombreChar = summonerName.ToCharArray();
foreach(Char caracter in nombreChar)
{
nombreRegex += "*";
nombreRegex += caracter;
}
//var filter = Builders<Summoner>.Filter.Regex(u => u.name, new BsonRegularExpression("/.*C*o*r*b*a*n/"));
BsonRegularExpression expReg = new BsonRegularExpression("/.*" + summonerName + "/");
var filter = Builders<Summoner>.Filter.Regex(u => u.name, expReg);
var resultado = collection.Find(filter).ToList();
if(resultado.Count() == 0)
{
InsertSummoner(RiotApiConnectorService.GetSummonerByName(summonerName));
GetSummonerByName(summonerName);
}
return resultado;
}
catch (Exception error)
{
return null;
}
}
有没有人在 C# 的 mongo 驱动程序中使用过正则表达式? 提前致谢!
【问题讨论】:
-
试试
new BsonRegularExpression(Regex.Escape(summonerName), "i") -
@WiktorStribiżew 现在正在工作,但缺少 like 运算符。如何在 Regex.Escape 中从 SQL 添加 LIKE 运算符?
-
“添加 LIKE”是什么意思?
LIKE不是正则表达式运算符,您不需要它。 -
@WiktorStribiżew 我的意思是,正则表达式中 SQL 中的等效 LIKE 运算符,类似于 %SummonerName%
-
这里不需要
%,因为正则表达式会找到部分匹配项(它不需要匹配整个字符串)。