0

From a String of <Meaning>Equal</Meaning>, how can I extract only the word Equal to another string?I tried using methods subStringBefore() and subStringAfter(), but is there any other way? The string is part of bigger string with similar tags.

7
  • It's not exactly clear what your goal is here. Given a string 'OneEqualTwo', do you want to get "Equal" as a result if the string contains the word "Equal", or remove "Equal" from the string so you're left with 'OneTwo'? Or am I not understanding your question and you're looking for something completely different?
    – Derek F
    Nov 2, 2023 at 20:28
  • Edited my question. Missed to add backtick , so the tags were not appearing in my question earlier. Nov 2, 2023 at 21:12
  • I want to get what comes in between the tags <Meaning> and </Meaning> Sorry for the confusion. Nov 2, 2023 at 21:19
  • Regular expression (RegEx) is the best functionality to use, but it does take some effort to learn. I like this tutorial. Nov 2, 2023 at 21:27
  • 1
    My question would be: is this potentially part of a larger XML document or document fragment? If so, have you considered using XML loading/parsing?
    – Phil W
    Nov 2, 2023 at 21:36

2 Answers 2

1

The following apex code can be used to extract 'Equal' enclosed between and tags :

String inputText = '<Meaning>Equal</Meaning>';
String patternString = '<Meaning>(.*?)</Meaning>';
String result = '';

System.Pattern patternTxt = System.Pattern.compile(patternString);
Matcher matcherTxt = patternTxt.matcher(inputText);

if (matcherTxt.find()) {
result = matcherTxt.group(1);
}

System.debug(result); // This will output 'Equal'
1
  • 1
    Thanks @Tanya Corporation. That worked perfect. Nov 3, 2023 at 18:56
2

I think that you want to ask is "how can I extract a string that I don't know from the middle of a string where I know its borders". Is this right? If so, then you can use removeStart and removeEnd to remove the <Meaning> and </Meaning>, respectively. This is assuming you know the contents of the borders in your string, but don't know what the content you want to get (the "Equal" string).

String s = '<b>text</b>';
String result = s.removeStart('<b>').removeEnd('</b>');

If you want to do this in a case-insensitive way, you can optionally replace those two with their counterparts removeStartIgnoreCase and removeEndIgnoreCase.

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .