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?
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
Why this is invalid in java?
List<String> items=new ArrayList<String>();
items.add("hello"); // valid
items.add('hello'); // invalid (error: invalid character constants)
Because '' single quotes are used for char variables.
Meaning 'a', 'b', and so on. So only one character per variable.
The double quotes on the other side "" are used to initialize String variables, which are several characters gathered together into one variable e.g "i am a string"
char c = 'c' // I use single quotes because I am single :)
String str = "This is a string" // I use double quotes because I got a lot in me
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Please, help me with how use java regular expression for the scenario described Specifically how to recognize a particular pattern to match:
I have an input string that may look something like this:
something + {SomeProductSet1}.count + {SomeOtherProductSet2}.amount >
{SomeProductSet3}.count + {SomeUSOC4}.amount
I need to replace everything in the {} with something like this
something + [abc].count+[xyz].count+[something].count + [xom].amount+
[ytkd].amount > [d].count
Basically, everything in between "{..}" has it's equivalent as a list of things that I put later using "[..]".
I have the list of things for [..] but, how can I "recognize" the '{...}' part It is of variable length and variable character sets.
What would I use as a pattern if using regular expressions ??
Thank you !! Much appreciated.
In Java there are lots of ways you can code to get the contents between brackets (or any two specific characters for that matter) but you sort of want to dabble with a regular expression which can be rather slow for this sort of thing especially when dealing with multiple instances of bracket pairs within a supplied string.
The basic code you want to gather up the contents contained between Curly Brackets could be something like this:
String myString = "something + {SomeProductSet1}.count + {SomeOtherProductSet2}.amount > \n" +
" {SomeProductSet3}.count + {SomeUSOC4}.amount";
Matcher match = Pattern.compile("\\{([^}]+)\\}").matcher(myString);
while(match.find()) {
System.out.println(match.group(1));
}
What the above Regular Expression means:
\\{ Open Curly Bracket character {
( start match group
[ one of these characters
^ not the following character
} with the previous ^, this means "every character except the Close
Curly Bracket }"
+ one of more other characters from the [] set
) stop match group
\\} literal Closing Curly Bracket }
If it were me, I would create a method to house this code so that it can be used for other bracket types as well like: Parentheses (), Square Brackets [], Curly Brackets {} (as shown in code), Chevron Brackets <>, or even between any two supplied characters like: /.../ or %...% or maybe even A...A. See the example method below which demonstrates this.
In the example code above it would be within the while loop where you would handle each substring found between each set of brackets. You will of course require a mechanism to determine which substring detected is to be replaced with whatever string like perhaps a multidimensional Array, or perhaps even a custom dialog which would display the found substring between each bracket and allow the User to select its replacement from perhaps a Combo Box with a Do All option Check Box. There are of course several options here for how and what you want to handle each found substring between each set of brackets.
Here is a method example which demonstrates what we've discussed here. It is well commented:
public String replaceBetween(String inputString, String openChar,
String closeChar, String[][] replacements) {
// If the supplied input String contains nothing
// then return a Null String ("").
if (inputString.isEmpty()) { return ""; }
// Declare a string to hold the input string, this way
// we can freely manipulate it without jeopordizing the
// original input string.
String inString = inputString;
// Set the escape character (\) for RegEx special Characters
// for both the openChar and closeChar parameters in case
// a character in each was supplied that is a special RegEx
// character. We'll use RegEx to do this.
Pattern regExChars = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
String opnChar = regExChars.matcher(openChar).replaceAll("\\\\$0");
String clsChar = regExChars.matcher(closeChar).replaceAll("\\\\$0");
// Create our Pattern to find the items contained between
// the characters tht was supplied in the openChar and
// closeChar parameters.
Matcher m = Pattern.compile(opnChar + "([^" + closeChar + "]+)" + clsChar).matcher(inString);
// Iterate through the located items...
while(m.find()) {
String found = m.group(1);
// Lets see if the found item is contained within
// our supplied 2D replacement items Array...
for (int i = 0; i < replacements.length; i++) {
// Is an item found in the array?
if (replacements[i][0].equals(found)) {
// Yup... so lets replace the found item in our
// input string with the related element in our
// replacement array.
inString = inString.replace(openChar + found + closeChar, replacements[i][1]);
}
}
}
// Return the modified input string.
return inString;
}
To use this method you might do this:
// Our 2D replacement array. In the first column we place
// the substrings we would like to find within our input
// string and in the second column we place what we want
// to replace the item in the first column with if it's
// found.
String[][] replacements = {{"SomeProductSet1", "[abc]"},
{"SomeOtherProductSet2", "[xyz]"},
{"SomeProductSet3", "[xom]"},
{"SomeUSOC4", "[ytkd]"}};
// The string we want to modify (the input string):
String example = "something + {SomeProductSet1}.count + {SomeOtherProductSet2}.amount > \n" +
" {SomeProductSet3}.count + {SomeUSOC4}.amount";
// Lets make the call and place the returned result
// into a new variable...
String newString = replaceBetween(example, "{", "}", replacements);
// Display the new string variable contents
// in Console.
System.out.println(newString);
The Console should display:
something + [abc].count + [xyz].amount >
[xom].count + [ytkd].amount
Notice how it also replaces the Curly Brackets? This appears to be one of your requirements but can be easily modified to just replace the substring between the brackets. Perhaps you can modify this method (if you like) to do this optionally and as yet another added optional feature....allow it to ignore letter case.
I tried to split a string and added it to a linked list. Each node in the linked list is a polynomial boundary. I tried this but it gave me a dangling meta character exception, what did I do wrong?
String s = "X^2+3x+5";
LinkedList p_list = new LinkedList();
s.toLowerCase();
s.replace("*x", "x");
s.replace("x^", "x");
s.replaceAll("--","+");
s.replaceAll("+-", "-");
s.replaceAll(" ", "");
String [] st = s.split("(?=[+-])");
String [] st2 = new String[2];
for(int i=0;i<=st.length;i++){
if(st[i].contains("x")){
st2=st[i].split("x");
if(st2[0].length()== 0 && st2[1].length()== 0){
p_list.addFirst(1,1);
}else if(st2[0].length()== 1 && st2[1].length()== 0){
p_list.addFirst(Integer.parseInt(st2[0]),0);
}
} else {
p_list.addFirst(Integer.parseInt(st2[0]),Integer.parseInt(st2[1]));
}
}
p_list.printList();
replace accepts a String, but replaceAll accepts a regex, and a regex that begins with + is invalid. You have two options:
escape the character +, in Java it's \\+
use Pattern#quote
Important note: String is immutable, you should assign the result to a new String.
The stack trace is pretty self-explanatory:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta
character '+' near index 0
+-
^
You need to escape the + symbol in the following line:
s = s.replaceAll("\\+-", "-"); // Note: you need to assign the result back to 's'
Not the answer (you already got 2 of them) but very important to note that String is immutable so the manipulation methods (e.g. toLowerCase, replace etc..) will produce a new string and will not modify the String object on which they are called so assign the result to your string in order for the changes to be in effect, i.e:
s = s.toLowerCase();
First of all String is immutable, so:
String s = "X^2+3x+5";
s.toLowerCase();
s.replaceAll(....)
s.substring(etc ...)
Will give you same String as declared at the beginning. The replaceAll() method takes a regex as the first parameter. And the "*" has special meaning in a regex. You will need to escape it with \.
String result = s.toLowerCase().replaceAll("\\*x", "x")
.replace("x^", "x").replaceAll("--", "+")
.replaceAll("\\+-", "-").replaceAll("\\+-", "-")
.replaceAll(" ", "");
i wanted to check if string contains operand
char m='\0';
char match[]={'(',')','=',';','{','}','[',']','+','-
','*','/','&','!','%','^','|','<','>'};
for(int i =0; i<code.length(); i++)
{
m=code.charAt(i);
for(int j=0;j<match.length;j++){
if(m==match[j]){
o++;
}
}
}
The above code can get the total no of operand use in string, but is there some easy way.
You can use regular expression to do the same thing with one line of code.
if(code.matches("[,/!%<>]")) sysout("There is Operator");
Place all the operators you need in between brackets.
I couldn't test above code now, but you may have to escape some operators using a back slash.
You can use a regular expression character class to find any of a list of characters, e.g.:
// (See note below about these -++--++
// || ||
// vv vv
if (stringToTest.match("[()=;{}[\\]+\\-*/&!%^|<>']")) {
// It has at least one of them
}
The [ and ] indicate a character class. Within that, you have to escape ] (because otherwise it looks like the end of the character class) with a backslash, and since backslashes are special in string literals, you need two. Similarly, you have to escape - within a character class as well (unless it's the first char, but it's easier just to remember to do it). I've highlighted those with tickmarks above.
Docs:
String#match
Pattern
java.util.regex
Try to use these functions
String.contains() - which checks if the string contains a specified sequence of char values
String.indexOf() - which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
instead of checking each char in array.
If you store "match" as a hash table, your lookups will be more efficient:
HashSet<Character> match = new HashSet<Character>(Arrays.asList('(',')','=',';','{','}','[',']','+','-','*','/','&','!','%','^','|','<','>');
for(int i =0; i < code.length(); i++) {
if (match.contains(code.charAt(i)) {
o++;
}
}
How would I remove all square brackets ("[]") from a given String in Java?
String s = "[abcdefg]";
s = s.replaceAll(regex, "");
What regular expression would be used in this case?
Use this one:
String s = "[abcdefg]";
String regex = "\\[|\\]";
s = s.replaceAll(regex, "");
System.out.println(s);
you could match it using something like "\\[([^\\]])\\]" (opening brachet, a sequence of anything that isnt a closing bracket (encased inside () for later reference), followed by a closing bracket) and then replace the whole match (group 0) with the contents matched inside the () block (group 1)