Java Online Compiler
Example: Remove Brackets using replaceAll in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Remove Brackets using replaceAll import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Define the algebraic expression String expressionWithBrackets = "(2 * {a + [b - c]} / 4)"; System.out.println("Original Expression: " + expressionWithBrackets); // Step 2: Define the regular expression to match all bracket types // The pattern "[{}\\[\\]()]" matches any of {, }, [, ], (, ) // Note: '[' and ']' are special characters in regex and need to be escaped with '\\' String regex = "[{}\\[\\]()]"; // Step 3: Use replaceAll() to remove all matching bracket characters String expressionWithoutBrackets = expressionWithBrackets.replaceAll(regex, ""); // Step 4: Print the modified expression System.out.println("Expression without Brackets (replaceAll): " + expressionWithoutBrackets); // Example with another expression String anotherExpression = "({x + y} / (z - 1)) * [p + q]"; System.out.println("\nOriginal Expression: " + anotherExpression); System.out.println("Expression without Brackets (replaceAll): " + anotherExpression.replaceAll(regex, "")); } }
Output
Clear
ADVERTISEMENTS