I have a String template like this:
"Thanks, this is your value : [value]. And this is your account number : [accountNumber]"
And i have inputs like this:
input 1 : "Thanks, this is your value : 100. And this is your account number : 219AD098"
input 2 : "Thanks, this is your value : 150. And this is your account number : 90582374"
input 3 : "Thanks, this is your value : 200. And this is your account number : 18A47"
I want output like this:
output 1 : "[value] = 100 | [accountNumber] = 219AD098"
output 2 : "[value] = 150 | [accountNumber] = 90582374"
output 3 : "[value] = 200 | [accountNumber] = 18A47"
How to do that? Maybe using Regex?
note : the template is not fixed.. the only thing that fixed is [value] and [accountNumber]..
use this regex
(?<=value : )(\d+)|(?<=number : )(.+)(?=")
this will extract both the values from the lines that you want. after getting them you can concatenate them with anything you want like your output string.
the code to use this regex will be like this
Pattern pattern = Pattern.compile("(?<=value : )(\d+)|(?<=number : )(.+)(?=\")");
Matcher matcher = pattern.matcher(SOURCE_TEXT_LINE);
List<String> allMatches = new ArrayList<String>();
while (matcher.find()) {
allMatches.add(matcher.group());
}
so this way you will get the matched values in this array list, of you can use a simple array if you prefer.
String text = "Thanks, this is your value : 100. And this is your account number : 219AD098";
Pattern pattern = Pattern
.compile("Thanks, this is your value : (\\d+). And this is your account number : (\\w+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
String outputText = "[value] = " + matcher.group(1)
+ " | [accountNumber] = " + matcher.group(2);
System.out.println(outputText);
is is easy to do without regex too:
String input = getInput();
String[] inputLines = input.split("\n");
String output = "";
int counter = 1;
for(string line : inputLines)
{
int subValStart = line.indexOf("value : ");
string val = line.substring(subValStart, line.indexOf("|") - subValStart);
string accNum = line.substring("account number : ");
output += "output " + counter + " :\"[value] = "+ val + " | [accountNumber] = " + accNum + "\"\n";
counter++;
}
Try this, StringUtils.subStringBefore
String sCurrentLine = CURRENT_LINE;
String[] splitedValue = sCurrentLine.split(":");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(splitedValue[0].replace("input", "output"));
stringBuilder.append(": \"[value] = "+StringUtils.substringBefore(splitedValue[2], "."));
stringBuilder.append(" | [accountNumber] = "+splitedValue[3]);
You can use regular expression.
Here is full example
package snippet;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws CoffeeDOMException, IOException {
String test = "Thanks, this is your value : 100 . And this is your account number : 219AD098";
String valueExpression = "\\svalue\\s:([^.]+)";
String accExpresion = "\\saccount\\snumber\\s:([^$]+)";
System.out.println("Value:" + runSubRegex(valueExpression, test));
System.out.println("Account:" + runSubRegex(accExpresion, test));
}
private static String runSubRegex(String regex, String tag) {
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(tag);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
Output
Value: 100
Account : 219AD098
Just check it out.
String template = "Thanks, this is your value : -XXXX-. And this is your account number : -XXXX- -XXXX- Value,Account Number";
String input = "Thanks, this is your value : 100. And this is your account number : 219AD098";
/*String template = "You can use -XXXX- mehod to read values from -XXXX- Value 1,value 2";
String input = "You can use this mehod to read values from custom string template";*/
String[] splitValue = template.split("-XXXX-");
for (String splitValueTemp : splitValue) {
input = input.replace(splitValueTemp, "!");
}
List<String> value = Arrays.asList(input.split("!"));
List<String> Key = Arrays.asList(splitValue[splitValue.length - 1].split(","));
if (value != null && value.size() > 1) {
int iCnt = 0;
for (String opValue : value.subList(1, value.size())) {
if (Key.size() > iCnt) {
System.out.println(Key.get(iCnt).trim() + " : " + opValue.trim());
}
iCnt++;
}
}
O/P:
Value : 100
Account Number : 219AD098
Related
I am trying to separate these value into ID, FullName and Phone. I know we can split it by using java split function. But is there any other ways to separate it? Values:
1 Peater John 2522523254
10 Neal Tom 2522523254
11 Tom Jackson 2522523254
111 Jack Smith 2522523254
12 Brownson Black 2522523254
I tried to use substring method but it won't work properly.
String id = line.substring(0, 3);
If I do this then it will work till 4th line, but other won't work properly.
If it is fixed length you can use String.substring(). But you should also trim() the result before you try to convert it to numeric:
String idTxt=line.substring(0,4);
Long id=Long.parseLong(idTxt.trim());
String name=line.substring(5,25).trim(); // or whatever the size is of name column.
You can use regex and Pattern
Pattern pattern = Pattern.compile("(\\d*)\s*([\\w\\s]*)\\s*(\\d*)");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
string id = matcher.group(0);
string name = matcher.group(1);
string phone = matcher.group(2);
}
package Generic;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main
{
public static void main(String[] args)
{
String txt=" 12 Brownson Black 2522523254";
String re1=".*?"; // Non-greedy match on filler
String re2="(\\d+)"; // Integer Number 1
String re3="(\\s+)"; // White Space 1
String re4="((?:[a-z][a-z]+))"; // Word 1
String re5="(\\s+)"; // White Space 2
String re6="((?:[a-z][a-z]+))"; // Word 2
String re7="(\\s+)"; // White Space 3
String re8="(\\d+)"; // Integer Number 2
Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find())
{
int id = Integer.parseInt(m.group(1));
String name =m.group(3) + " ";
name = name+m.group(5);
long phone = Long.parseLong(m.group(7));
System.out.println(id);
System.out.println(name);
System.out.println(phone);
}
}
}
What about this:
int first_space;
int last_space;
first_space = my_string.indexOf(' ');
last_space = my_string.lastIndexOf(' ');
if ((first_space > 0) && (last_space > first_space))
{
long id;
String full_name;
String phone;
id = Long.parseLong(my_string.substring(0, first_space));
full_name = my_string.substring(first_space + 1, last_space);
phone = my_string.substring(last_space + 1);
}
Use a regexp:
private static final Pattern RE = Pattern.compile(
"^\\s*(\\d+)\\s+(\\S+(?: \\S+)*)\\s+(\\d+)\\s*$");
Matcher matcher = RE.matcher(s);
if (matcher.matches()) {
System.out.println("ID: " + matcher.group(1));
System.out.println("FullName: " + matcher.group(2));
System.out.println("Phone: " + matcher.group(3));
}
You can use a StringTokenizer for this. You won't have to worry about amount of spaces and/or tabs before or after your values, and no need for complex regex expressions:
String line = " 1 Peater John\t2522523254 ";
StringTokenizer st = new StringTokenizer(line, " \t");
String id = "";
String name = "";
String phone = "";
// The first token is your id, you can parse it to an int if you like or need it
if(st.hasMoreTokens()) {
id = st.nextToken();
}
// Loop over the remaining tokens
while(st.hasMoreTokens()) {
String token = st.nextToken();
// As long a there are other tokens, you're processing the name
if(st.hasMoreTokens()) {
if(name.length() > 0) {
name = name + " ";
}
name = name + token;
}
// If there are no more tokens, you've reached the phone number
else {
phone = token;
}
}
System.out.println(id);
System.out.println(name);
System.out.println(phone);
I have got a String in this format
FUTSTKACC28-APR-2016
ACC is a symbol and 28-APR-2016 is a expiry date
FUTSTK is predefined word
How to retrieve values symbol and Date in this case
For example how to get
ACC
and
28-APR-2016
some sample data
FUTSTKACC26-MAY-2016
FUTSTKACC28-APR-2016
FUTSTKACC30-JUN-2016
FUTSTKADANIENT26-MAY-2016
FUTSTKADANIENT28-APR-2016
FUTSTKADANIENT30-JUN-2016
You have a fixed length prefix word and a fixed length date. You can remove the prefix, and then take the substrings from the right by the 11 characters in your dates. Something like,
String[] sample = { "FUTSTKACC26-MAY-2016", "FUTSTKACC28-APR-2016",
"FUTSTKACC30-JUN-2016", "FUTSTKADANIENT26-MAY-2016",
"FUTSTKADANIENT28-APR-2016", "FUTSTKADANIENT30-JUN-2016" };
String predefWord = "FUTSTK";
for (String input : sample) {
if (input.startsWith(predefWord)) {
input = input.substring(predefWord.length());
// There are 11 characters in the date format
String symbol = input.substring(0, input.length() - 11);
String dateStr = input.substring(input.length() - 11);
System.out.printf("symbol=%s, date=%s%n", symbol, dateStr);
}
}
Output is
symbol=ACC, date=26-MAY-2016
symbol=ACC, date=28-APR-2016
symbol=ACC, date=30-JUN-2016
symbol=ADANIENT, date=26-MAY-2016
symbol=ADANIENT, date=28-APR-2016
symbol=ADANIENT, date=30-JUN-2016
Something like this should work:
final String PATTERN = "(FUTSTK)(.+)(\d\d-\w\w\w-\d\d\d\d)"
Pattern p = Pattern.compile(PATTERN);
Matcher m = p.matcher("FUTSTKACC28-APR-2016");
String symbol = m.group(1);
DateFormat format = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date date = format.parse(string);
final String str = "FUTSTKACCCCCCC28-APR-2016";
final String[] strArr = str.split("-");
final String month = strArr[0].substring(strArr[0].length() - 2);
final String word = strArr[0].substring(0, strArr[0].length() - 2);
System.out.println("word: " + word);
System.out.println("date: " + month + "-" + strArr[1] + "-" + strArr[2]);
A regex approach (bits stolen from #ElliottFrisch) assuming you know the predefined word:
String[] sample = { "FUTSTKACC26-MAY-2016", "FUTSTKACC28-APR-2016",
"FUTSTKACC30-JUN-2016", "FUTSTKADANIENT26-MAY-2016",
"FUTSTKADANIENT28-APR-2016", "FUTSTKADANIENT30-JUN-2016" };
String predefined = "FUTSTK";
Pattern p = Pattern.compile(Pattern.quote(predefined) + "(\\w+)(\\d\\d-\\w\\w\\w-\\d\\d\\d\\d)");
for (String s: sample) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1) + " " + m.group(2));
}
}
output:
ACC 26-MAY-2016
ACC 28-APR-2016
ACC 30-JUN-2016
ADANIENT 26-MAY-2016
ADANIENT 28-APR-2016
ADANIENT 30-JUN-2016
I have this string: "23+43*435/675-23". How can I split it? The last result which I want is:
String 1st=23
String 2nd=435
String 3rd=675
String 4th=23
I already used this method:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = s.split("\\-");
String[] split2 = s.split("\\*");
String[] split3 = s.split("\\/");
String plus = split[1];
String minus = split1[1];
String multi = split2[1];
String div = split3[1];
System.out.println(plus+"\n"+minus+"\n"+multi+"\n"+div+"\n");
But it gives me this result:
pLus-minuss*multi/divide
minuss*multi/divide
multi/divide
divide
But I require result in this form
pLus
minuss
multi
divide
Try this:
public static void main(String[] args) {
String s ="23+43*435/675-23";
String[] ss = s.split("[-+*/]");
for(String str: ss)
System.out.println(str);
}
Output:
23
43
435
675
23
I dont know why you want to store in variables and then print . Anyway try below code:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String first =ss[1];
String second =ss[2];
String third =ss[3];
String forth =ss[4];
System.out.println(first+"\n"+second+"\n"+third+"\n"+forth+"\n");
}
Output:
pLus
minuss
multi
divide
Try this out :
String data = "23+43*435/675-23";
Pattern pattern = Pattern.compile("[^\\+\\*\\/\\-]+");
Matcher matcher = pattern.matcher(data);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
for (int index = 0; index < list.size(); index++) {
System.out.println(index + " : " + list.get(index));
}
Output :
0 : 23
1 : 43
2 : 435
3 : 675
4 : 23
I think it is only the issue of index. You should have used index 0 to get the split result.
String[] split = s.split("\\+");
String[] split1 = split .split("\\-");
String[] split2 = split1 .split("\\*");
String[] split3 = split2 .split("\\/");
String hello= split[0];//split[0]=hello,split[1]=pLus-minuss*multi/divide
String plus= split1[0];//split1[0]=plus,split1[1]=minuss*multi/divide
String minus= split2[0];//split2[0]=minuss,split2[1]=multi/divide
String multi= split3[0];//split3[0]=multi,split3[1]=divide
String div= split3[1];
If the order of operators matters, change your code to this:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = split[1].split("\\-");
String[] split2 = split1[1].split("\\*");
String[] split3 = split2[1].split("\\/");
String plus = split1[0];
String minus = split2[0];
String multi = split3[0];
String div = split3[1];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
Otherwise, to spit on any operator, and store to variable do this:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String plus = ss[1];
String minus = ss[2];
String multi = ss[3];
String div = ss[4];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
}
I am using the below regex expression :
Pattern p = Pattern.compile("(.*?)(\\d+)?(\\..*)?");
while(new File(fileName).exists())
{
Matcher m = p.matcher(fileName);
if(m.matches()) { //group 1 is the prefix, group 2 is the number, group 3 is the suffix
fileName = m.group(1) + (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) + (m.group(3)==null ? "" : m.group(3));
}
}
This works fine for filename like abc.txt but if there is any file with name abc1.txt the above method is giving abc2.txt. How to make the regex condition or change (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) so that it returns me abc1_copy1.txt as new filename and not abc2.txt and so forth like abc1_copy2 etc.
Pattern p = Pattern.compile("(.*?)(_copy(\\d+))?(\\..*)?");
while(new File(fileName).exists())
{
Matcher m = p.matcher(fileName);
if (m.matches()) {
String prefix = m.group(1);
String numberMatch = m.group(3);
String suffix = m.group(4);
int copyNumber = numberMatch == null ? 1 : Integer.parseInt(numberMatch) + 1;
fileName = prefix;
fileName += "_copy" + copyNumber;
fileName += (suffix == null ? "" : suffix);
}
}
I'm not a java guy, but in general, you should use libarary functions/classes for parsing filenames as many platforms have different rules for them.
Look at:
http://people.apache.org/~jochen/commons-io/site/apidocs/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String)
I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}