Regex pattern to replace ampersand with special character - java

I need to replace https://9S&Re with https://9S#Re so that I can avoid split logic. My objective is it get key as "user_image" and value as "https://9S&Re". But when I use split with '&' it gives me wrong results. So I am trying for regex pattern which will check between &*& if there is not equals inbetween means there is an ampersand symbol in the one of the query value. Any help is really appreciated.
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public class OAuthTest {
public static void main(String[] args) {
try {
//HashMap paramHashMap=new HashMap();
List<NameValuePair> args2= URLEncodedUtils.parse("tool=canvas&tool_guid=8314&user_image=https://9S&Re&launch_presentation_document_target=iframe", Charset.forName("UTF-8"));
for (NameValuePair arg:args2)
System.out.println(arg.getName()+"="+arg.getValue().replaceAll("#","&"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

In the for loop, are you trying to replace & with #? Your arguments are switched.

Related

Read comma separated values from a text file in Java and find the maximum number from each line

I used the following code to read all the lines. Now as I understand it I should somehow parse the numbers from each line and apply a function to get the maximum value. The problem is I do not know how to go about it and I do not know what to search for in google. The problem is one of unknown unknowns. Some pointers would be helpful.
import java.io.IOException;
import java.util.List;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.ArrayList;
public class KnowNotTest1 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Using Path.readAllLines()");
try{
List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
fileData.forEach(System.out::println);
}
catch (IOException e){
System.out.println(e);
}
}
}
The text file I am reading is as below:
10,11,12
2,13
33,22,1,1
1
And the expected output is:
12
13
33
1
Without checking the input file is correct
readAllLines(Paths.get("/tmp/lines.txt")).stream()
.mapToInt(s -> Arrays.stream(s.split(","))
.mapToInt(Integer::parseInt).max().getAsInt())
.forEach(System.out::println);
the previous one is the best one to do, not directly (there are three important and decoupled parts: read, compute and report) also, it open te door to process in a efficient, online, streaming way (readAllLines break it).
An imperative way is
for(String line: readAllLines(Paths.get("/tmp/lines.txt"))) {
int max = Integer.MIN_VALUE;
for (String word : line.split(","))
max = Math.max(max, Integer.parseInt(word));
System.out.println(max);
}
but is coupled and not compose.
Use mapToXX method of stream api :
public class KnowNotTest1 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Using Path.readAllLines()");
try{
List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
System.out.println("Input: ");
fileData.forEach(System.out::println);
System.out.println("Output: ");
fileData.stream()
.mapToLong(
s -> Arrays.stream(s.split(","))
.mapToLong(Long::parseLong).max()
.getAsLong()).forEach(System.out::println);
}
catch (IOException e){
System.out.println(e);
}
}

Does java support duplicate subpattern group number in regex?

I am trying to get a single match with regex which contains both parts of the string at once like "BERPAR" in the following text:
{"from":"BER", "comment":"something", "to":"PAR" }
I came up with this (?|from":"([A-Z]{3})"|to":"([A-Z]{3})"), which apparently works fine with PCRE as you can see here
But in the code, I get an error with Java compiler.
Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown inline modifier near index 2
(?|from":"([A-Z]{3})"|to":"([A-Z]{3})")
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
String str = "{\"from\":\"BER\", \"comment\":\"something\", \"to\":\"PAR\" }";
System.out.println(str);
Pattern p = Pattern.compile("(?|from\":\"([A-Z]{3})\"|to\":\"([A-Z]{3})\")");
Matcher m = p.matcher(str);
List<String> results = new ArrayList<>();
while(m.find()) {
results.add(m.group(1));
}
System.out.println(results);
}
}
link to the online ide to see the error: http://tpcg.io/DWoebEWG
any solution or workaround would be appreciated.
Please note that the objective is Only use regex. It's first matching group should return "BERPAR"
PLEASE NOTE THAT THIS REGEX IS SUPPOSED TO BE PARSED BY A JAVA APPLICATION I DO NOT HAVE ANY OPTION TO WRITE JAVA CODE FOR IT!
THE ABOVE CODE SNIPPET IS FOR DEMONSTRATION PURPOSE ONLY!
Please note that the objective is Only use regex. It's first matching
group should return "BERPAR"
You can get it by using ((?<=from\":\")|(?<=to\":\"))([A-Z]{3})(?=\") as the regex.
Demo:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld {
public static void main(String[] args) {
String str = "{\"from\":\"BER\", \"comment\":\"something\", \"to\":\"PAR\" }";
System.out.println(str);
Pattern p = Pattern.compile("((?<=from\":\")|(?<=to\":\"))([A-Z]{3})(?=\")");
Matcher m = p.matcher(str);
List<String> results = new ArrayList<>();
while (m.find()) {
results.add(m.group());
}
System.out.println(results);
// Join the strings of the list
String joined = String.join("", results);
System.out.println(joined);
}
}
Output:
{"from":"BER", "comment":"something", "to":"PAR" }
[BER, PAR]
BERPAR

Why is my ArrayList Empty?

I am working on Project Euler problem 13. ( https://projecteuler.net/problem=13 ) The file "Large_Num_List.txt" is the list provided by the project Euler with each number on its own line with a quote mark at the beginning and end of each line. The statement bial.isEmpty() returns true. Why is this happening? (I suspect because this is my first time using Scanner to read a text file.)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
import java.util.Iterator;
public class LargeSumTwo
{
public static void main(String[] args)
{
ArrayList<BigInteger> bial = new ArrayList<BigInteger>();
File file = new File("Large_Num_List.txt");
try
{
Scanner scan = new Scanner(file);
while(scan.hasNextBigInteger())
{
bial.add((BigInteger) scan.nextBigInteger());
}
scan.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println(bial.isEmpty());
BigInteger answer = new BigInteger("0");
Iterator<BigInteger> iter = bial.iterator();
while(iter.hasNext())
{
answer.add(iter.next());
}
System.out.println(answer);
}
}
You need to strip the quotes first. hasNextBigInteger() will only return true if Scanner can parse a BigInteger. The quotes around the numbers will cause hasNextBigInteger() to return false.
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29
Should you add BigInteger in this way:
while(iter.hasNext())
{
answer = answer.add(iter.next());
}
as BigDecimal numbers are immutable?

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 ?

Splitting String into Array of Strings Java

I have a String that looks like this
The#red#studio#502#4
I need to split it into 3 different Strings in the array to be
s[0] = "The red studio"
s[1] = "502"
s[2] = "4"
The problem is the first one should have only words and the second and third should have only numbers...
I was trying to play with the s.split() Method, but no luck.
String s= "The#red#studio#502#4";
String[] array = s.split("#(?=[0-9])");
for(String str : array)
{
System.out.println(str.replace('#',' '));
}
Output:
The red studio
502
4
Ideone link.
I've decided to edit out my impl because I think that #Srinivas's is more elegant. I'm leaving the rest of my answer though because the tests are still useful. It passes on #Srinivas's example too.
package com.sandbox;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
#Test
public void testQuestionInput() {
String[] s = makeResult("The#red#studio#502#4");
assertEquals(s[0], "The red studio");
assertEquals(s[1], "502");
assertEquals(s[2], "4");
}
#Test
public void testAdditionalRequirement() {
String[] s = makeResult("The#red#studio#has#more#words#502#4");
assertEquals(s[0], "The red studio has more words");
assertEquals(s[1], "502");
assertEquals(s[2], "4");
}
private String[] makeResult(String input) {
// impl inside
}
}
Simply try:
'String s[]= yourString.split("#")' it will return string array....

Categories

Resources