I have this code to
public static String ProcessTemplateInput(String input, int count) {
Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String newelem=SelectRandomFromTemplate(matcher.group(1), count);
}
return input;
}
Input is:
String s1 = "planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.} Is this ok? ";
Output example:
String s2="planets Sun, Mercury. Is this ok? ";
I would like to replace the {} set of templates with the picked value returned by the method. How do I do that in Java1.5?
Use appendReplacement/appendTail:
StringBuffer output = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(output, SelectRandomFromTemplate(matcher.group(1), count));
}
matcher.appendTail(output);
return output.toString();
Related
I'm trying to pick out the characters of a string that come just before and just after the part of the string that matches another string, creating a completely different string. I.e. when the method wordEnds(String str, String word) is called, and str = "XY1XY" and word = "XY", then the new string would be "11".
Here is what I have so far:
package codingBat;
public class CodingBat {
public static String wordEnds(String str, String
word) {
String newStr = null;
if(str.equals(word)) {
return "";
}
else if(!str.contains(word)) {
return "";
}
else {
for(int i = 0;i < str.length();i++) {
if((word.equals(str.substring(i,i+1)))){
newStr = newStr + (str.substring(i-1,i+2));
}
else {
return newStr;
}
}
return newStr;
}
}
}
Try to use regex, pattern for your example ll look like this XY.*XY. But You have to change the XYto the string parameter so it ll be pattern = str+"(.*)"+str. Then you can use the group and read the string from middle
Here is a code:
static String middleString(String str, String word) {
Pattern pattern = Pattern.compile(str + "(.*)" + str);
Matcher matcher = pattern.matcher(word);
matcher.matches();
return matcher.group(1);
}
This call:
System.out.println(middleString("XY", "XY11XY"));
Returns 11
" 294618 is your One Time Passcode (OTP) for the request "
How to extract only the numbers from the String given above?
Following function will return you the first integer that is part of string.
public static String getOtp(String string) {
String sPattern = "[^0-9]*([0-9]+).*";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
String s = matcher.group(1);
return s;
}
return null;
}
This will print out all numbers from your String:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(" 294618 is your One Time Passcode (OTP) for the request ");
while(m.find()) {
System.out.println(m.group());
}
String yourString = "294618 is your One Time Passcode (OTP) for the request";
String extractNo= yourString.replaceAll("[^0-9]", "");
System.out.println(extractNo);
I was trying to get an int (serial number of a student) from a string looks like "122. Fardinabir 170213" , where "122" is his serial number.
Before this, I tried using nextInt() method with a Scanner of the String, but nextInt() failed to do the job.
Then I have tried this procces...
import java.util.Scanner;
public class tempfile {
public static void main(String[] args) {
int serial_int = 0;
String serial_st;
serial_st = find_serial("122. FardinAbir 170213") ;
System.out.println(serial_st);
serial_int = Integer.parseInt(serial_st);
System.out.println(serial_int);
}
public static String find_serial(String st)
{
String[] parts = st.split(" "); // the first serial part will remain in parts[0]
parts[0].replaceAll("[\\D]", ""); // As I know it will remove non integer and the pure int serial will remain
return parts[0];
}
}
But, replaceAll("[\\D]", "") is not working...
Can anyone please help me to solve this or find a way out to this job...
Thanks in advance...
String line = "122. FardinAbir 170213";
Pattern pattern = Pattern.compile("^(\\d+)");
Matcher matcher = pattern.matcher(line);
if(matcher.find()) {
int id = Integer.parseInt(matcher.group(1));
System.out.println(id);
}
Assuming you also want to get the rest of the string eventually you can use Regex groups
String line = "122. FardinAbir 170213";
Pattern pattern = Pattern.compile("(\\d+)\\.\\s+([^\\s]+)\\s+(\\d+)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("serial: " + matcher.group(1));
int serial = Integer.parseInt(matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
nextInt() probably did not work because scanner expects newline separation
Since you tried using nextInt it seems you just want leading digits, which means you can use the following regex code:
public static String find_serial(String st) {
Matcher m = Pattern.compile("^\\d+").matcher(st);
return (m.find() ? m.group() : null);
}
You could also rely in the serial ending with a period, though that doesn't validate that serial is all digits:
public static String find_serial(String st) {
int idx = st.indexOf('.');
return (idx > 0 ? st.substring(0, idx) : null);
}
This'll do:
public static int getSerialNumber() {
String id = "122. Fardinabir 170213";
int place = 0;
for(int i = 0; i < id.length();i++) {
if(id.charAt(i) == '.') {
place = i;
break;
}
}
return Integer.parseInt(id.substring(0, place));
}
EDIT: you can also do it like this:
public static int getSerialNumber(String name) {
return Integer.parseInt(name.substring(0, name.indexOf('.')));
}
thanks #Andreas for that solution.
I am trying to remove zeros in value using regex(non capturing group). Does anyone have an idea?
Matcher matcher = Pattern.compile("(?:[0]+)?(\\S+)").matcher("00100");//.group(0));
//Matcher matcher = pattern.matcher(mydata);
if(matcher.matches()) {
System.out.println("value "+matcher.group(0));
}
str.replaceAll("^0+(?!$)", "")
If you want to remove leading zeroes, you can just use replaceAll:
String input = "00100";
input = input.replaceAll("^0+([^0].*)$", "$1");
Regex101
I found a solution to my own question:
public static void main(String[] args) {
extractValuesFromRegex("(?:0+|)(\\d+)", "00123");
extractValuesFromRegex("(?:0+|)(\\d+)", "123");
extractValuesFromRegex("(\\d+)", "00123");
extractValuesFromRegex("(\\d+)", "00123");
}
public static final String extractValuesFromRegex(String regex, String input) {
String extractevalue = input;
Matcher matcher = Pattern.compile(regex).matcher(input);
if (matcher.matches()) {
extractevalue = matcher.group(1);
}
return extractevalue;
}
I have a string as follows:
"This is #awesome #dude"
From this string i want to extract awesome and dude and create a string
output==> "awesome,dude"
So my code is like following:
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(textStr);
while (matcher.find()){
mergedStr += matcher.group() +",";
}
But this creates an artifact in the end
output==> "awesome,dude," //<-- egghh comma.. in the end
What is a better way to solve this out.
Another approach:
boolean needComma = false;
while (blah, blah, blah) {
if (needComma) {
string += ",";
}
string += word;
needComma = true;
}
But there are a dozen different approaches.
This is one option:
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(textStr);
while (matcher.find()){
if (!mergedStr.isEmpty())
mergedStr += ",";
mergedStr += matcher.group();
}
Here is another common approach:
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(textStr);
StringBuilder sb = new StringBuilder();
while (matcher.find()){
sb.append(matcher.group()).append(",");
}
return sb.toString().replaceAll(",$", "");
If you don't want to use a regex, you could do it like this:
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(textStr);
StringBuilder sb = new StringBuilder();
while (matcher.find()){
sb.append(matcher.group()).append(",");
}
if (sb.length() == 0) {
return "";
}
else {
return sb.toString().substring(0, sb.length() - 1);
}
A useful pattern that I often use for this kind of thing is to append the first item, and then append the remainder of the items preceded by the separator. This avoids unnecessary conditionals in loops or postprocessing to remove trailing separators.
I know, microoptimizations blah, blah, sixth circle of hell, blah, blah, but just including here for your amusement:
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(textStr);
StringBuilder mergedStr = new StringBuilder();
if (matcher.find()) {
mergedStr.append(matcher.group());
while (matcher.find()) {
mergedStr.append(',').append(matcher.group());
}
}
return mergedStr.toString();
Also, I'm not 100% convinced that replacing a quadratic algorithm (string concatenation) with a linear algorithm (StringBuilder) qualifies as a microoptimization in the bad sense.
String input = "#awesome#dude";
List<String> strSplit = new ArrayList<String>();
String result = "";
Matcher matcher = Pattern.compile("(?<=#)\\w+").matcher(input);
while (matcher.find()){
strSplit.add(matcher.group());
}
for(int j = 0; j< strSplit.size(); j++){
result = result + strSplit.get(j);
if(j < strSplit.size() -1){
result = result+",";
}
}
System.out.println("Result : " + result);