How to remove every sequence of "()" in a string in java? - java

I'm trying to remove every sequence of () in my string.
For example my String is:
String a = "() a)";
And I want it to become
" a)"
When I tried this it gave me an infinite loop
public static String removeParentheses(String s) {
while (s.contains("()")) {
s = s.replaceAll("()", "");
}
return s;
}

String replaceAll method require regexp in parameter. In your case you provide empty group. To use string as parameter you can use replace method like:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replace("()", "");
assert Objects.equals(result, "asaassaaassasax");
}
Or change the regexp to correct form using \ character in way:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replaceAll("\\(\\)", "");
assert Objects.equals(result, "asaassaaassasax");
}

According the documentation of String.replaceAll, the first argument is a regular expression.
This means () is not being treated literally, it's being treated as an empty capture group, which effectively matches nothing. I think what you're looking for is the normal String.replace method. I'm aware that the names of these methods seem to imply that replace only replaces one instance while replaceAll replaces all of them, but this is not the case.
public static String removeParentheses(String s) {
return s.replace("()", "");
}
JDoodle deomonstrating code above
If for some reason you would like to continue using replaceAll instead, you can dynamically escape the pattern using Pattern.quote.
public static String removeParentheses(String s) {
String pattern = Pattern.quote("()");
return s.replaceAll(pattern, "");
}
JDoodle demonstrating code above

Related

removing characters from string using a method in java

I'm trying to write a method to take in a string as a parameter and remove all whitespaces and punctuation from it so this is my idea of how to do that..
import java.util.*;
public class Crypto {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please insert the text you wish to encrypt: ");
String text = input.nextLine();
text = normalizeText(text);
System.out.println(text);
}
public static String normalizeText(String s){
s.replace(" ","");
s.replace("(","");s.replace(")","");s.replace(".","");
s.replace(",","");s.replace("?","");s.replace("!","");
s.replace(":","");s.replace("'","");s.replace("\"","");
s.replace(";","");
s.toUpperCase();
return s;
}
}
Now , I only added the text = normalize Text(text); and then printed it because it wouldn't print it to the screen without it( even though in some methods the return would actually show an output on the screen)
anyway, even this change didn't help because it doesn't remove anything from the string taken in by the method it prints out the exact same string.. any help?
Thanks in advance . :)
Problem in your code is, you haven't assigned back the new string that got generated after s.replace(":",""); Remember, strings are immutable so the change by replace method will not apply to the string object on which you call the method.
You should have written,
s = s.replace(":", "")
Instead of your tedious method normalizeText you can write your method like this,
public static String normalizeText(String s){
return s.replaceAll("[ ().,?!:'\";]", "").toUpperCase();
}
You need to make assignments to the string after each replacement has been made, e.g.
public static String normalizeText(String s) {
s = s.replace(" ", "");
s = s.replace("(","");
// your other replacements
s = s.toUpperCase();
return s;
}
But note that we can easily just use a single regex to handle your replacement logic:
public static String normalizeText(String s) {
s = s.replaceAll("[().,?!:'\"; ]", "").toUpperCase();
return s;
}

Java - Insert String into another String after string pattern?

I'm trying to figure out how to insert a specific string into another (or create a new one) after a certain string pattern inside the original String.
For example, given this string,
"&2This is the &6String&f."
How would I insert "&l" after all "&x" strings, such that it returns,
"&2&lThis is the &6&lString&f&l."
I tried the following using positive look-behind Regex, but it returned an empty String and I'm not sure why. The "message" variable is passed into the method.
String[] segments = message.split("(?<=&.)");
String newMessage = "";
for (String s : segments){
s.concat("&l");
newMessage.concat(s);
}
System.out.print(newMessage);
Thank you!
You can use:
message.replaceAll("(&.)", "$1&l")
(&.) finds pattern where an ampersand (&) is followed by anything. (&x as you've written).
$1&l says replace the captured group by the captured group itself followed by &l.
code
String message = "&2This is the &6String&f.";
String newMessage = message.replaceAll("(&.)", "$1&l");
System.out.println(newMessage);
result
&2&lThis is the &6&lString&f&l.
My answer would be similar to the one above. It just this way would be reusable and customizable in many circumstances.
public class libZ
{
public static void main(String[] args)
{
String a = "&2This is the &6String&f.";
String b = patternAdd(a, "(&.)", "&l");
System.out.println(b);
}
public static String patternAdd(String input, String pattern, String addafter)
{
String output = input.replaceAll(pattern, "$1".concat(addafter));
return output;
}
}

Remove double tag from string

I have a String look like this :
<start> <start> some sentence <stop> is a sentence <stop>
How I can make those String something like this :
<start> some sentence is a sentence <stop>
So far I'm using regex to remove the double start first
string.replace("<start> <start>","<start>");
but I'm still stuck at removing the middle stop tag.
Can do like below replaceFirst is String class method which replaces the first substring of this string that matches the given regular expression with the given replacement.
String finalResult=string.replaceFirst("<start>", "" ).replaceFirst("<stop>", "" )
If you are sure about Start and Stop Tags in Starting & Ending. You can also hardcode them manually and remove all the tags in-between.
public class myclass {
public static void main(String[] args) {
String x = "<start> <start> some sentence <stop> is a sentence <stop>";
String finalResult="<start>"+x.replaceAll("<[^>]+>", "")+"<stop>";
System.out.println(finalResult);
}
}
One way, you can just remove all of the instances and then fix the String how you want it:
private static final String START = "<start>";
private static final String STOP = "<stop>";
private boolean containsKeywords(final String string) {
return string.contains(START) ||
string.contains(STOP);
}
private String stripAllStartStop(final String string) {
string.replaceAll(START, "");
string.replaceAll(STOP, "");
}
private addStartStop(final String string) {
StringBuilder sb = new StringBuilder();
sb.add(START);
sb.add(string);
sb.add(STOP);
return sb.build();
}
/**
* Cleanup the sequence of START and STOP tokens in a String.
*/
public String sanitizeString(final String string) {
if (containsKeywords(string)) {
return addStartStop(stripAllStartStop(string));
}
}
The better, cleaner, and more extensible way is similar, but using StrSubstitutor using a lookup Map for the replacements.
The stop you want to remove is wrapped by empty spaces to the right AND left use that as criteria to remove the one you need..
string.replace(" <stop> ","");

Java check that string will only allow commas as special chacters

how can I check to make sure the only special character a string can have is a comma?
testString = "123,34565,222" //OK
testString = "123,123.123." //Fail
A full working example based on #Simeon's regex. This reuses a single Matcher object, which is recommended if the check will be done frequently.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class OnlyLettersDigitsCommas {
//"": Dummy search string, to reuse matcher
private static final Matcher lettersCommasMtchr = Pattern.
compile("^[a-zA-Z0-9,]+$").matcher("");
public static final boolean isOnlyLettersDigitsCommas(String to_test) {
return lettersCommasMtchr.reset(to_test).matches();
}
public static final void main(String[] ignored) {
System.out.println(isOnlyLettersDigitsCommas("123,34565,222"));
System.out.println(isOnlyLettersDigitsCommas("123,123.123."));
}
}
Output:
[C:\java_code\]java OnlyLettersDigitsCommas
true
false
You can use a quick String.contains method like this:
if ( testString.contains(".") {
// fails
}
But I would consider using Regex for this type of validation.
EDIT : As stated in the comments of the question : [a-zA-Z0-9,]
Maybe a
if (!testString.matches("^[a-zA-Z0-9,]+$")) {
// throw an exception
}
check ?

Search a string against another using Regex

I need to check whether a String is contained in another String.
For example, "abc" is contained in "abc/def/gh","def/abc/gh" but not in "abcd/xyz/gh","def/abcd/gh".
So, I have split the input String by "/". Then iterated the generated String array to check against the input.
Is it possible to avoid the creation of the array using something like Regex?
Also, could anybody confirm whether using Regex will be faster than the creation & iteration of array as I have used?
Thanks in advance
public class RegexTest {
public static void main(String[] args) {
System.out.println(contains("abc/def/gh", "abc"));
System.out.println(contains("def/abc/gh", "abc"));
System.out.println(contains("def/abcd/gh", "abc"));
System.out.println(contains("abcd/xyz/gh", "abc"));
}
private static boolean contains(String input, String searchString) {
String[] strings = input.split("/");
for (String string : strings) {
if (string.equals(searchString))
return true;
}
return false;
}
}
The console output is:
true
true
false
false
Something like this:
String pattern = "(.*/)?abc(/.*)?";
System.out.println("abc/def/gh".matches(pattern));
System.out.println("def/abc/gh".matches(pattern));
System.out.println("def/abcd/gh".matches(pattern));
System.out.println("abcd/xyz/gh".matches(pattern));
prints
true
true
false
false
Using regex is more convenient (?), but please time yourself whether it is faster:
if (!searchString.contains("/")) {
return input.matches("(.*/)?" + Pattern.quote(searchString) + "(/.*)?");
} else {
return false;
}
I made sure that the searchString does not contain /, before inserting it as literal with Pattern.quote. The regex will make sure that there is a / before and after the search string in the input, either that or the search string is the first or last token in the input.
try this regex
s.matches("^abc/.+|.+/abc/.+|.+/abc$")
or
s.startsWith("abc/") || s.contains("/abc/") || s.endsWith("/abc")

Categories

Resources