How to replace odd number of single quote with two single quote - java

I want to add escape character "'"(single quote) in string in java but only when there is odd number of occurrence using Regular Expression
For Ex:
if string is like "string's property" then output should be "string''s property"
if string is like "string''s property" then output should be "string''s property"

Try this :
\'(\')?
Demo (replacing with ')
http://regexr.com?38eeh

Try this code (even count).
public static void main(String[] args) {
String str = "a''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}
Then try this one (odd count).
public static void main(String[] args) {
String str = "a'''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}

Try this:
// input that will be replaced
String replace = "string's property";
// input that won't be replaced
String noReplace = "string''s property";
// String representation of the Pattern for both inputs
// |no single quote before...
// | |single quote
// | | |... no single quote after
String pattern = "(?<!')'(?!')";
// Will replace found text with main group twice --> found
System.out.println(replace.replaceAll(pattern, "$0$0"));
// Will replace found text with main group twice --> not found, no replacement
System.out.println(noReplace.replaceAll(pattern, "$0$0"));
Output:
string''s property
string''s property

Related

how to read a txt and delimit it by pipes

I have a txt file with the following form:
1 | Argentina |Y|POSTAL_C |CAPITAL|STATES
I would like to convert each of these positions separated by the "|", be it a position within an example array like this:
0 | 1 |2|3 |4 |5
1 | Argentina |Y|POSTAL_C |CAPITAL|STATES
and work them inside an array
My code
public void ReadFile2() throws IOException {
String referencePath = "C:\\Users\\Admin\\Desktop\\PRUEBA.txt";
BufferedReader br;
br = new BufferedReader(new FileReader(referencePath));
String lines = br.readLine();
lines.split("\n", 6);
this.logger.info("Starting...");
while (lines != null) {
if (!lines.isEmpty() && lines.length() >7) {
String[] values = lines.split("|");
System.out.println(values[0]); ----> should return 1
}
lines = br.readLine();
}
br.close();
}
grateful for your comments
Because String you pass to split method should be a regex you need to use lines.split("\\|").
In regex pipe sign have special meaning (it works like OR operator) so you need to escape it by backslash. In java string literal backslash have special meaning because it's escape following character so you that's way two backslashes here. Result String is in fact just \|.
Try this:
String test = "1 | Argentina |Y|POSTAL_C |CAPITAL|STATES";
String[] values = test.split("\\|");
for (String value : values) {
System.out.println(value);
}
This returns output:
1
Argentina
Y
POSTAL_C
CAPITAL
STATES
Probably you would like also to .trim() particular values to remove unnecessary white spaces.

Regex to remove line break within double quote in CSV

Hi I have a csv file with an error in it.so i want it to correct with regular expression, some of the fields contain line break, Example as below
"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre Pkwy
California",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"
the above two lines should be in one line
"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre PkwyCalifornia",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"
I tried to use the below regex but it didnt help me
%s/\\([^\"]\\)\\n/\\1/
Try this:
public static void main(String[] args) {
String input = "\"AHLR150\",\"CDS\",\"-1\",\"MDCPBusinessRelationshipID\","
+ ",,\"Investigating\",\"1600 Amphitheatre Pkwy\n"
+ "California\",,\"Mountain View\",,\"United\n"
+ "States\",,\"California\",,,\"94043-1351\",\"9958\"\n";
Matcher matcher = Pattern.compile("\"([^\"]*[\n\r].*?)\"").matcher(input);
Pattern patternRemoveLineBreak = Pattern.compile("[\n\r]");
String result = input;
while(matcher.find()) {
String quoteWithLineBreak = matcher.group(1);
String quoteNoLineBreaks = patternRemoveLineBreak.matcher(quoteWithLineBreak).replaceAll(" ");
result = result.replaceFirst(quoteWithLineBreak, quoteNoLineBreaks);
}
//Output
System.out.println(result);
}
Output:
"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre Pkwy California",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"
Create a RegEx surrounding the text you want to keep by parentheses and that will create a group of matched characters. Then replace the string using the group index to compose as you wish.
String test = "\"AHLR150\",\"CDS\",\"-1\",\"MDCPBusinessRelationshipID\","
+ ",,\"Investigating\",\"1600 Amphitheatre Pkwy\n"
+ "California\",,\"Mountain View\",,\"United\n"
+ "States\",,\"California\",,,\"94043-1351\",\"9958\"\n";
System.out.println(test.replaceAll("(\"[^\"]*)\n([^\"]*\")", "$1$2"));
So when we replace the matching string ("United\nStates") by $1$2 we are removing the line break because it not belongs to any group:
$1 => the first group (\"[^\"]*) that will match "United
$2 => the second group ([^\"]*\")" that will match States"
Based on this you can try with:
/\r?\n|\r/
I checked it here and seems to be fine

How can i split string in java using combine special characters

How can I split a String using combine special characters?
For example, if the combine Special characters is {#}:
String str = "This is test string1.{#}This is test string2#(#*$ ((##{}";
StringTokenizer stoken = new StringTokenizer(str, "\\{\\#\\}");
while (stoken.hasMoreElements()) {
System.out.println(stoken.nextElement());
}
What I expect from above program is :
This is test string1.
This is test string2#(#*$ ((##{}
You can not use characters with special meanings like : \ ^ $ . | ? * + ( ) [ { }, i think there are 12 of them. therefore change your character to split the string to something like "/-/"
the code to do so looks like the one underneath:
public class SplitString {
public static void main(String[] args) {
String s = "This is test string1./This is test string2#(#*$ ((##{}";
String[] fragments = s.split("/");
String fragment1 = fragments[0];
String fragment2 = fragments[1];
System.out.println(fragment1);
System.out.println(fragment2);
}
}
this solution is based on the answer in this thread:
Stackoverflow Split String

Splitting string into array of words using specific words java

I want to split this String to give my desired output
sinXcos(b+c)
Gives output as
sinX
cos(b+c)
I know how to split a string like
200XY
using
token = 200XY;
String[] mix_token = token.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
But how can I use something like this on a string like
sinXcos(b+c)
or a String like
sinXcos(b+c)tan(z)
This will work..
public static void main(String[] args) {
String text = "sinXcos(b+c)tan(z)";
String patternString1 = "(sin|cos|tan)(?![a-z])\\(?\\w(\\+\\w)?\\)?";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
O/P:
sinX
cos(b+c)
tan(z)
2. Input :"sinabc(X+y)cos(b+c)tan(z)";
O/P :
cos(b+c)
tan(z)
Explaination :
S
tring patternString1 = "(sin|cos|tan)(?![a-z])\\(?\\w(\\+\\w)?\\)?";
1. (sin|cos|tan) -->start with (sin or cos or tan)
2. (?:![a-z]) --> negative lookahead. check if the next character is not in between [a to z].
3. \\(?\\w(\\+\\w)?\\)?--> an optional brace followed by an alphabet followed by a "+" and another alphabet.

Regular Expression Statement

I've never been good with regex and I can't seem to get this...
I am trying to match statements along these lines (these are two lines in a text file I'm reading)
Lname Fname 12.35 1
Jones Bananaman 7.1 3
Currently I am using this for a while statement
reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")
But it doesn't enter the while statement.
The program reads the text file just fine when I remove the while.
The code segment is this:
private void initializeFileData(){
try {
Scanner reader = new Scanner(openedPath);
while(reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")){
employeeInfo.add(new EmployeeFile(reader.next(), reader.next(), reader.nextDouble(), reader.nextInt(), new employeeRemove()));
}
for(EmployeeFile element: employeeInfo){
output.add(element);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Use the \s character class for the spaces between words:
while(reader.hasNext("\\w+\\s\\w+\\s\\d*\\.\\d{1,2}\\s[0-5]"))
Update:
According to the javadoc for the Scanner class, by default it splits it's tokens using whitespace. You can change the delimiter it uses with the useDelimiter(String pattern) method of Scanner.
private void initializeFileData(){
try {
Scanner reader = new Scanner(openedPath).useDelimiter("\\n");
...
while(reader.hasNext("\\w+\\s\\w+\\s\\d*\\.\\d{1,2}\\s[0-5]")){
...
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
From what I can see (And correct me if I'm wrong, because regex always seems to trick my brain :p), you're not handling the spaces correctly. You need to use \s, not just the standard ' ' character
EDIT: Sorry, \s. Someone else beat me to it :p
Actually
\w+
is going to catch [Lname, Fname, 12, 35, 1] for Lname Fname 12.35 1. So you can just store reader.nextLine() and then extract all regex matches from there. From there, you can abstract it a bit for instance by :
class EmployeeFile {
.....
public EmployeeFile(String firstName, String lastName,
Double firstDouble, int firstInt,
EmployeeRemove er){
.....
}
public EmployeeFile(String line) {
//TODO : extract all the required info from the string array
// instead of doing it while reading at the same time.
// Keep input parsing separate from input reading.
// Turn this into a string array using the regex pattern
// mentioned above
}
}
I created my own version, without files and the last loop, that goes like that:
private static void initializeFileData() {
String[] testStrings = {"Lname Fname 12.35 1", "Jones Bananaman 7.1 3"};
Pattern myPattern = Pattern.compile("(\\w+)\\s+(\\w+)\\s+(\\d*\\.\\d{1,2})\\s+([0-5])");
for (String s : testStrings) {
Matcher myMatcher = myPattern.matcher(s);
if (myMatcher.groupCount() == 4) {
String lastName = myMatcher.group(1);
String firstName = myMatcher.group(2);
double firstValue = Double.parseDouble(myMatcher.group(3) );
int secondValue = Integer.parseInt(myMatcher.group(4));
//employeeInfo.add(new EmployeeFile(lastName, firstName, firstValue, secondValue, new employeeRemove()));
}
}
}
Notice that I removed the slash before the dot (you want a dot, not any character) and inserted the parenthesis, in order to create the groups.
I hope it helps.

Categories

Resources