Home > Software design >  Getting substring from a string after and before particular characters
Getting substring from a string after and before particular characters

Time:10-28

I have a string of some random length (not specified as requirement).

Example:

dev.ca.ind.clientaddress-completed-events.dom.0.ind-isl-clientaddress-completed.dlq

Here, I have to skip three strings, i.e. dev.ca.ind. (I want what is after these strings and before this) .dom, i.e. clientaddress-completed-events (I want to fetch this string from that whole string)

Second example:

dev.ca.ind.insurance.client.insurance.dom.0

I want to fetch insurance.client.insurance after ind and before dom and also this ind can also be gb,grs,all,ind. And dom can also be raw,cdc.

How do I do this? I am unable to get idea on how to do this.

I have tried splitting these string with "." but pattern is different for some string as shown in example and this is creating some bugs, so I thought of this way, but wasn't able to implement.

String[] splitName = topics.get(PROJECT i).get(TOPIC_NAME).split("\\.");

but it was not good as I have to assign substrings using hardcoded index values, e.g. ss.set(splitName[2] splitName[3]).

Some more examples:

dev.ca.xfunc.cxo.rawleads.dom.0 - get "cxo.rawleads"
dev.ca.epm.ceapm.zab.dom.0 - get "ceapm.zab"
dev.ca.ind.cx.talas.cdc.0 - get "cx.talas"
dev.ca.cif.source-system-client.dom.0 -get "source-system-client"

dev.ca.gb.claim.providers.int.0 -get "claim.providers"

CodePudding user response:

You'll have to test all cases of prefixes and suffixes:

private static String removePrefix(String s) {
    return Stream.of("gb", "grs", "all", "ind")
            .map(suffix -> "dev.ca."   suffix)
            .filter(s::startsWith)
            .findFirst()
            .map(p -> s.substring(p.length() 1))
            .orElseThrow(() -> new IllegalStateException("Invalid String"));
}

private static String removeSuffix(String s) {
    return Stream.of(".dom", ".raw", ".cdc")
            .filter(s::contains)
            .findFirst()
            .map(p -> s.substring(0, s.indexOf(p)))
            .orElseThrow(() -> new IllegalStateException("Invalid String"));
}

and do

removeSuffix(removePrefix(s))

CodePudding user response:

If it were me, I would use the split function that returns an array of elements like so:

String target = "dev.ca.ind.clientaddress-completed-events.dom.0.ind-isl-clientaddress-completed.dlq"    
String keyTokens = target.split(".")

That will give you a keyTokens array of items like so: "dev" "ca" "ind" "clientaddress-completed-events" "dom" "0" "ind-isl-clientaddress-completed" "dlq"

Then walk the array looking for the first String where "isInteger" returns true.

  • Related