简体   繁体   English

如何从字符串中提取单词

[英]How to extract a word from a string

We have some logging service from an API that's having some trouble catching the database a query is accessing. 我们有一个来自API的日志服务,在捕获查询正在访问的数据库时遇到了一些麻烦。

Say, a query comes like this: 假设查询如下:

Select Top 10 * From DataBase..Table

What I'd like to achieve is to get "DataBase" or the text prior to the ".." on the string. 我想要实现的是在字符串上获取“ DataBase”或“ ..”之前的文本。

Also, sometimes a query comes like this: 另外,有时会出现如下查询:

Select Top 10 * From DataBase.Schema.Table

Is it possible to get the "DataBase" string on both cases? 在两种情况下都可以获取“ DataBase”字符串吗?

Here's what I've been trying to do, but I not that good in regular expressions. 这是我一直在尝试做的事情,但是我在正则表达式中的表现并不理想。

([A-Z]+\.+?([A-Z])*(\.)+[A-Z])

But this matches the following (on square brackets): 但这与以下内容匹配(在方括号中):

Select Top 10 * From [DataBase..T]able

Thanks for the help! 谢谢您的帮助!

Edit: This is done in C#, prior to sending the query/request to the database, we are trying to log every request this API method processes. 编辑:这是在C#中完成的,在将查询/请求发送到数据库之前,我们正在尝试记录此API方法处理的每个请求。

As it is mentioned in comment, parsing SQL this way is a bad idea due complexities that you can encounter. 正如注释中提到的那样,由于可能会遇到复杂性,因此以这种方式解析SQL是一个坏主意。 But if this is something you want to do, following should work. 但是,如果这是您想做的事情,那么应该可以执行以下操作。 It will work for select or delete statements, insert/update won't work as they have different structure. 它适用于选择或删除语句,因为它们具有不同的结构,所以插入/更新将不起作用。

public string GetDbName(string sql)
{
    var sqlLower = sql.ToLower();
    var parts = sqlLower.Split(new string[] { "from " }, StringSplitOptions.RemoveEmptyEntries);

    if (parts.Length < 2)
    {
        //something is wrong in sql;
        //may be its not a select statement
        return null;
    }

    var tableName = parts[1]
        .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        .FirstOrDefault();

    var posOfTableName = tableName.LastIndexOf('.');
    var dbName = tableName.Substring(0, posOfTableName);

    //We can return here, but it will return lower case db name parts
    //We can also get the original value as well by looking into original parameter
    var indexOfStart = sqlLower.IndexOf(dbName);
    return sql.Substring(indexOfStart, dbName.Length);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM