Saurabh Gaur Saurabh Gaur - 2 months ago 12
Groovy Question

How to get non-alphabetical separator char from string

I have a situation where I want to get separator char from the given string like as below :-

String str1 = "saurabh|om|anurag|abhishek|jitendra"

String str2 = "amit,ankur,sumit,aniket,suheel"

String str3 = "aj-kumar-manav-lalit-gaurav"

-------


In above strings I want to get separator char as :-

String separatorStr1 = "|"
String separatorStr2 = ","
String separatorStr3 = "-"


Note :- separator char always will be non-alphabetical in string

Is there any way to achieve this.

Answer

Using groovy regexp and find ([^\w] is any non-alphanumeric character)

def getSeparator = { str ->
    str.find(~/[^\w]/)
}

String str1 = "saurabh|om|anurag|abhishek|jitendra"
String str2 = "amit,ankur,sumit,aniket,suheel"
String str3 = "aj-kumar-manav-lalit-gaurav"

assert getSeparator(str1) == '|'
assert getSeparator(str2) == ','
assert getSeparator(str3) == '-'