Java - Insert String into another String after string pattern? - java

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;
}
}

Related

How to remove every sequence of "()" in a string in 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

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;
}

how to replace multiple strings with replace method at once without making more string objects

I got a string test "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}". what I want is that I want to replace things in angular brackets with dynamic values. Sample code:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String toBeReplaced0 = "alpha";
String toBeReplaced1 = "beta";
String toBeReplaced2 = "gama";
String test = "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}";
}
}
Now in this code I want to replace <userName> with alpha, <firstName> with beta, <lastName> with gama at once without making multiple string objects. This is not a homework question. test string can have more angular elements in it to be filled with dynamic values. How can I do this with replace method or any thing else..
Matcher.appendReplacement could be an option. Example:
public static void main(String[] args){
String toBeReplaced0 = "alpha";
String toBeReplaced1 = "beta";
String toBeReplaced2 = "gama";
String test = "{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}";
System.out.println(findAndReplace(test,toBeReplaced0,toBeReplaced1,toBeReplaced2));
}
public static String findAndReplace(String original, String... replacments){
Pattern p = Pattern.compile("<[^<]*>");
Matcher m1 = p.matcher(original);
// count the matches
int count = 0;
while (m1.find()){
count++;
}
// if matches count equals replacement params length replace in the given order
if(count == replacments.length){
Matcher m = p.matcher(original);
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
m.appendReplacement(sb, replacments[i]);
i++;
}
m.appendTail(sb);
return sb.toString();
}
//else return original
return original;
}
If that's JSON, I'd prefer to use a JSON library to dynamically construct the resultant string and mitigate any possible syntactic errors.
If you really want to use String.replaceAll() or similar, I wouldn't expect that to be a problem in the above limited scope. Simply chain together your calls (e.g. see this tutorial)
Note that strings are immutable, and as such you can't easily do this without creating new string objects. If that's really a concern, perhaps you need to modify an array of chars (but that will be a non-trivial task when substituting multiple strings of varying lengths differing from their placeholders).
Simply:
String result = orig.replace("<userName>", "replacement");
(not forgetting that strings are immutable and so you have to use the result returned from this call)
I would do that with the StringTemplate library. With your example works out of the box:
<dependency>
<groupId>org.antlr</groupId>
<artifactId>ST4</artifactId>
<version>4.0.8</version>
<scope>compile</scope>
</dependency>
// Given
final ST template = new ST("{\"userName\": \"<userName>\",\"firstName\": \"<firstName>\",\"lastName\": \"<lastName>\"}");
template.add("userName", "alpha");
template.add("firstName", "beta");
template.add("lastName", "gamma");
// When
final String result = template.render();
// Then
Assert.assertEquals("{\"userName\": \"alpha\",\"firstName\": \"beta\",\"lastName\": \"gamma\"}", result);

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> ","");

How to find the first character of a String without using any API method

Recently I was being asked this question in an interview:
Find the first character of a String without using any method from String class
Gave the following approaches, assuming str as a String:
str.charAt(0)
str.toCharArray()[0]
str.substring(0,1)
Can anyone suggest me the way it can be achieved?
Using Matcher API (and not String): we create a pattern that captures every character but only find the first one and print it (the dotall mode is enabled to handle the case where the first character is a line separator).
public static void main(String[] args) {
Matcher matcher = Pattern.compile("(.)", Pattern.DOTALL).matcher("foobar");
if (matcher.find()) {
System.out.println(matcher.group(1)); // prints "f"
}
}
s.charAt(0) uses CharSequence API, not String, so formally it is correct answer.
Another option is to use a method accepting CharSequence as argument, e. g. one of Commons Lang StringUtils'.
Using reflection you could gain access to
private final char value[];
array from String class which stores all characters. So your code could look like:
String str = "abc";
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
char[] chars = (char[]) f.get(str);
System.out.println(chars[0]);
Output: a.
Also technically StringBuilder API is not the same as String so we could also use
String str = "abc";
System.out.println(new StringBuilder(str).charAt(0));
// ^-comes from StringBuilder, not String
Another silly solution using a custom writer:
private class PseudoWriter extends Writer {
private Character first;
public void write(char[] cbuf, int off, int len) throws IOException {
if (first == null) {
first = cbuf[off];
}
}
public void flush() throws IOException {}
public void close() throws IOException {}
public Character getFirstChar() {
return first;
}
}
Usage:
String s = "Lorem ipsum";
PseudoWriter pseudoWriter = new PseudoWriter();
pseudoWriter.write(s);
Character first = pseudoWriter.getFirstChar();
You can use a StringReader and read the first character:
char firstChar = (char) new StringReader(str).read();

Categories

Resources