I want to get the index of first digit in my string using painless script. Can someone please assist me on how I can achieve it?
I did try search() function but looks like it is not supported by painless, as below script gave me error as "reason": "dynamic method [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;
Thanks, Nivedita
As you already saw, the search function is not exposed to the painless context. But since you are searching for a restricted set of characters, you could also work with indexOf
and Math.min
function.
The idea is that each character may either be in the string (delivering a positive indexOf) or not (delivering a negative value). You can basically iterate over the searched characters and take the smaller value (bigger than -1).
You could write something like:
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;
Obviously, is not as clean as with search but is a viable workaround (given the simplicity of the regexp you are using).
Regards,