【问题标题】:how to get index of first digit in string in painless script?如何在无痛脚本中获取字符串中第一个数字的索引?
【发布时间】:2022-06-15 01:15:39
【问题描述】:

我想使用无痛脚本获取字符串中第一个数字的索引。有人可以帮助我如何实现它吗?

我确实尝试了 search() 功能,但似乎无痛不支持,因为下面的脚本给了我错误“原因”:“动态方法 [java.lang.String, search/1] not found”

def str = doc['index.keyword'].value;
def value = "";
if (str != null)
{
def indexFirstNumber = str.search(/[0-9]/);
value = str.substring(0, indexFirstNumber);
}
return value;

谢谢, 尼维迪塔

【问题讨论】:

    标签: elasticsearch-painless


    【解决方案1】:

    正如您已经看到的,搜索功能不会暴露在无痛上下文中。但由于您正在搜索一组受限制的字符,您也可以使用 indexOfMath.min 函数。

    这个想法是每个字符可能在字符串中(传递正 indexOf)或不在字符串中(传递负值)。您基本上可以遍历搜索到的字符并取较小的值(大于-1)。

    你可以这样写:

    def str = ...;
    def lv = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    def res = str.length() + 1;
    def tmp = -1;
    for (v in lv) {
        tmp = str.indexOf(v);
        if (tmp >= 0) { // the index is in the string
            res = (int) Math.min(res, tmp);
        }
    }
    return res;
    

    显然,它不像搜索那样干净,但它是一种可行的解决方法(考虑到您使用的正则表达式的简单性)。

    问候,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 2023-04-07
      • 2014-05-05
      • 2017-09-05
      • 2011-05-29
      • 2010-10-21
      • 2017-07-27
      相关资源
      最近更新 更多