1

String :

The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color

using the Regex : (<.*?>)

i was able to get the tags like <ex id=\"3\"/> and <g id=\"4\">

but how can we remove all the string part from the sentence so that the final string would look like <ex id=\"3\"/><g id=\"4\"></g><g id=\"5\">

with only the tags.

Q: Remove anything from the sentence but tags (NOT operator for tags).

1
  • 1
    Use same regex in Matcher.find() and get your new string using matcher.group(0) Commented Feb 9, 2021 at 7:24

2 Answers 2

4

The below code creates a new string with the required tags.

public static void main(String[] args)
{
    String line = "The car has <ex id=\\\"3\\\"/><g id=\\\"4\\\">attributes</g><g id=\\\"5\\\">, such as weight and color";
    String regex = "(<.*?>)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(line);
    StringBuilder compactline = new StringBuilder();
    while (matcher.find()) {
        compactline.append(matcher.group());
    }
    System.out.println("Original Line : " + line);
    System.out.println("Compact Line : " + compactline);
}

Output

Original Line : The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color

Compact Line : <ex id=\"3\"/><g id=\"4\"></g><g id=\"5\">
Sign up to request clarification or add additional context in comments.

Comments

0
String  segment ="The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color;
String regex="(<.*?>)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher=pattern.matcher(segment);
   while(matcher.find())
      {
        System.out.println("matcher ="+matcher.group());
      }

Output :

matcher =<ex id=\"3\"/>
matcher =<g id=\"4\">
matcher =</g>
matcher =<g id=\"5\">
matcher =</g>
matcher =<g id=\"6\">
matcher =</g>
matcher =<g id=\"7\">
matcher =</g>

On trying the suggestion by @anubhava This code snippet worked and fetched only the tags present in the string .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.