mmar
mmar

Reputation: 2020

how to substring and extract a dynamic content

i have a string which loads on the page based on the success and failure search results. If the search case is success then my output table will have a string like

Search Results - 31 Items Found (Debug Code: 4b50016efc3a1ad93502)

or if my search results fail, then the output table will display a string either:

Search Results - No data found (Debug Code: 4b50016efc3a1ad93502)
Search Results - 0 Items Found (Debug Code: 4b50016efc3a1ad93502)
Search Results - An Exception Occurred (Debug Code: 4b50016efc3a1ad93502)

depending on the input conditions.

I want to extract the Debug Code value and pass on to other scenario to validate further. I know I can use substring() to extract the Debug Code, but its position in the string is not constant; it varies based on the input conditions, however Debug code will be at last.

How can I extract the Debug Code value (eg 4b50016efc3a1ad93502) for all scenarios?

Upvotes: 1

Views: 746

Answers (2)

Bohemian
Bohemian

Reputation: 425198

You can use regex to capture and return the target code:

String debugCode = output.replaceAll(".*Debug Code: (\\w+).*|.*", "$1");

What's happening here?

The regex .*Debug Code: (\\w+).* matches the entire string, and captures (with brackets) the target text using \\w+, which means "one or more 'letter' characters" ('letters' included digits). The replacement string $1 means "group 1" - the first captured group. Because the entire input is matched, this operation effectively replaces the whole input with the captured group, so returns just the target text.

So what happens if the input doesn't have a debug code?

The extra |.* at the end of the regex means "or 'anything'", so the regex will match the entire input even if there it doesn't have a debug code, but captured group 1 will still exist, but it will be empty, so the operation returns the blank string.

Examples:

String output1 = "Results - 0 Items Found (Debug Code: 4b50016efc3a1ad93502)";
String output2 = "something else";

String code1 = output1.replaceAll(".*Debug Code: (\\w+).*|.*", "$1"); // "4b50016efc3a1ad93502"
String code2 = output2.replaceAll(".*Debug Code: (\\w+).*|.*", "$1"); // ""

You don't have to use "|.*", but you don't have it, the entire string will be returned if the input doesn't have the 'debug code' format.

Upvotes: 3

NomadMaker
NomadMaker

Reputation: 448

A java String is invariant. No matter how you get a String, its contents will not change.

For example

String s = "the way we were";
String t = s.substring(4, 6);   // t = "way"
s = "abcdefghijk";

s is a new String, but t is unchanged

Upvotes: 0

Related Questions