Home > OS >  how to check for brackets outside two quotes in a String
how to check for brackets outside two quotes in a String

Time:08-18

i have for instance a String : if('{' == '{'){. i would want it to not detect the brackets inside the ' ' but i do want it to detect the one at the end which is not inside the quotes what the best way of doing i tried to loop through all chars but is there a quicker method?

CodePudding user response:

You can simply remove those braces altogether or replace them with something meaningful. To just remove those '{' and '}' characters from the string then you could do it like this using the String#replaceAll() method which accepts a Regular Expression (regex), for example:

// Original String:
String strg1 = "if('{' == '{'){";
    
/* Apply change and place into a new string (strg2) 
   so to keep old string original (in strg1).    */
String strg2 = strg1.replaceAll("'\\{'|'\\}'", "");
    
// Display the new String strg2:
System.out.println(strg2);

The Console Window will display:

if( == ){

The regex "'\\{'|'\\}'" used above basically does the following:

Replace All instances of '{' OR | All instances of '}' within the string with Null String "" (nothing). Within the Expression, the curly braces are escaped \\{ because they have special meaning within a Regular Expression and by escaping those characters informs regex processing that we mean literal character.

If you want to replace those '{' and '}' character combinations with something meaningful like specific values then you can replace those items separately, for example:

// Original String:
String strg1 = "if('{' == '}'){";
int value1 = 10;  // An open brace ( '{' ) will be converted to this value
int value2 = 24;  // A close brace ( '}' ) will be converted to this value
    
/* Apply change and place into a new string (strg2) 
   so to keep old string original (in strg1).    */
String strg2 = strg1.replaceAll("'\\{'", String.valueOf(value1))
                    .replaceAll("'\\}'", String.valueOf(value2));
    
// Display the new String strg2:
System.out.println(strg2);

The console window will display:

if(10 == 24){

In the above code you will of noticed that the String#valueOf() method was used within the replacement section of the String#replaceAll() method. This is because the replacement values we want to use were declared as int data types and the replaceAll() method requires String as a replcement argument therefore we take those int values and convert them to String type.

  • Related