Java: Easiest way to replace strings with random strings
A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.
ex: ax 5 5 dx 3 acc c ax bx
I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.
replacement example: acc 5 5 dx 3 acc c ax bx or c 5 5 dx 3 acc c ax ax
Is there a way to do this with regexes? In Java? If so, which methods should I use?
Asked by: Alford851 | Posted: 21-01-2022
Answer 1
I think this is the most clean solution for replacing a certain set of symbols from a string containing a superset of them.
appendreplacement is the key to this method.
one important caveat: do not include any unescped dollar characters ($) in your elements list. escape them by using "\$"
eventually use
.replaceall("\$","\\$");
on every string before adding it to the list.
see also the javadoc in doubt about the $ signs.
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReplaceTokens {
public static void main(String[] args) {
List<String> elements = Arrays.asList("ax", "bx", "dx", "c", "acc");
final String patternStr = join(elements, "|"); //build string "ax|bx|dx|c|acc"
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher("ax 5 5 dx 3 acc c ax bx");
StringBuffer sb = new StringBuffer();
Random rand = new Random();
while (m.find()){
String randomSymbol = elements.get(rand.nextInt(elements.size()));
m.appendReplacement(sb,randomSymbol);
}
m.appendTail(sb);
System.out.println(sb);
}
/**
* this method is only needed to generate the string ax|bx|dx|c|acc in a clean way....
* @see org.apache.commons.lang.StringUtils.join for a more common alternative...
*/
public static String join(List<String> s, String delimiter) {
if (s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuffer buffer = new StringBuffer(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
Answered by: Alissa359 | Posted: 22-02-2022
Answer 2
To answer the first question: no.
Since you are doing a random replace, regex will not help you, nothing about regex is random. * Since your strings are in an array, you don't need to find them with any pattern matching, so again regex isn't necessary.
**Edit: the question has been edited so it no longer says the strings are in an array. In this case, assuming they are all in one big string, you might build a regex to find the parts you want to replace, as shown in other answers.*
Answered by: Julian171 | Posted: 22-02-2022Answer 3
- Yes, this can be done with regexes. Probably not very prettily, not without a loop or two
- Yes, this can be implemented in Java.
- See Random, the regex package
- The implementation is left as an exercise for the student.
Answer 4
Use the Random class to generate a random int to choose the index of the symbols.
String text = "ax 5 5 dx 3 acc c ax bx";
System.out.println("Original: " + text);
String[] tokens = text.split(" ");
List<Integer> symbols = new ArrayList<Integer>();
for(int i=0; i<tokens.length; i++) {
try {
Integer.parseInt(tokens[i]);
} catch (Exception e) {
symbols.add(i);
}
}
Random rand = new Random();
// this is the part you can do multiple times
int source = symbols.get((rand.nextInt(symbols.size())));
int target = symbols.get((rand.nextInt(symbols.size())));
tokens[target] = tokens[source];
String result = tokens[0];
for(int i=1; i<tokens.length; i++) {
result = result + " " + tokens[i];
}
System.out.println("Result: " + result);
Make as many replacements as you need before you join the tokens back together.
There are two parts here that might seem tricky. First, the try catch to identify those tokens that are not integers. I recommend you pull that part out into its own method, since it works, but it's a bit hacky.
The second is where I set the source
and target
variables. What I'm doing there is getting a randomly selected index of one of the non-numeric symbols. Once I have two random indexes, I can swap them in the next line.
An alternative would be, to build up a new String from randomly selected symbols after you've split the original String into an array.
Answered by: Hailey429 | Posted: 22-02-2022Answer 5
thanks a bunch guys. here's what i came up with. see if you can come up with a more efficient way.
private final String[] symbolsPossible = {"ax","bx","cx","dx","foo"};
private boolean exists;
private final String mutate(String s)
{
String[] tokens=s.split(" ");
for(int j=0; j<tokens.length; j++)
if(Math.random()<.1) //10% chance of mutation per token
{
//checking to see if the token is a supported symbol
exists=false;
for(int i=0; i<symbolsPossible.length; i++)
if(tokens[j].equals(symbolsPossible[i]))
exists=true;
if(exists)
tokens[j]=symbolsPossible[(int)Math.random()*symbolsPossible.length];
}
StringBuffer result=new StringBuffer();
for(String t:tokens)
result.append(t);
return result;
}
Answered by: Michelle179 | Posted: 22-02-2022
Similar questions
java - An editor for a data object in swing, what is the easiest way?
I have a java object with several members. I want to create a small, quick and dirty editor that allows me to set the value of the members in an easy way. I've created a Panel that contains a TextField for every member. I have a setValues() method that will take the value of the TextFields and set them into the object. This method is automatically invoked when I call getDataObject() from the panel. Some of the members...
Easiest way to fetch SSL page via a proxy in Java
I would like to fetch a SSL page in Java. The problem is, that I have to authenticate against a http proxy.
So I want a simple way to fetch this page.
I tried the Apache Commons httpclient, but it's too much overhead for my problem.
I tried this piece of code, but it does not contain an authentication action:
import java.io.*;
import java.net.*;
public class ProxyTest {
public static voi...
Easiest way to compare two Excel files in Java?
I'm writing a JUnit test for some code that produces an Excel file (which is binary). I have another Excel file that contains my expected output. What's the easiest way to compare the actual file to the expected file?
Sure I could write the code myself, but I was wondering if there's an existing method in a trusted third-party library (e.g. Spring or Apache Commons) that already does this.
What is the easiest way to call a Java method from C++?
I'm writing a C++ program which needs to be able to read a complex and esoteric file type. I already have a Java program for handling these files which includes functionality to convert them into simpler file formats. My idea is, whenever my program needs to read info from a complex file, to have it call the Java method to convert it to the simpler file type, then write it out to a temp file which my program can easily r...
java - What is the easiest way to merge two flv videos?
what is the easiest way to merge two flv videos into one?
Would be awesome if its possible without command-line-tools like ffmpeg.
It would be great if someone knows a simple java solution =)
(on the server side)
What's the easiest way to extract the JPG data from an MP3 header in java?
I wrote a JSP that hands my Flash front-end an XML file that describes the contents of my mp3 folder, but am stuck trying to parse the individual file headers for the album art that is embedded therein. Can anyone recommend a good library that has something straight forward that in pseudo code would look like...
String mp3FilePath = "/mp3s/foo.mp3";
File myJpg = getImageFromMP3(mp3FilePath);
...
Easiest way to call Java from C#?
We have a major body of code in Java that runs on the desktop that we want to reuse with a MS.NET user interface (desktop rather than web). Any do's or don'ts would be very welcome.
java - What is the easiest way to draw texture with OpenGL ES?
I saw this Google IO session: http://code.google.com/intl/iw/events/io/2009/sessions/WritingRealTimeGamesAndroid.html
He says that the draw_texture function is the fastest and VBO is 2nd faster.
But I don't understand how to use it(the draw_texture method or the VBO way).
Any suggestion?
java - Easiest way to get Enum in to Key Value pair
I have defined my Enums like this.
public enum UserType {
RESELLER("Reseller"),
SERVICE_MANAGER("Manager"),
HOST("Host");
private String name;
private UserType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
What should be the easiest way to get a key-value pair form the enum values?
The output map...
class - Java: easiest way to package both Java 1.5 and 1.6 code
I want to package a piece of code that absolutely must run on Java 1.5. There's one part of the code where the program can be "enhanced" if the VM is an 1.6 VM.
Basically it's this method:
private long[] findDeadlockedThreads() {
// JDK 1.5 only supports the findMonitorDeadlockedThreads()
// method, so you need to comment out the following three lines
if (mbean.isSynchronizerU...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)