I want to replace all occurrences of single quotations with two quotations, except in first and last occurrence, I managed to get to exclude the last occurrence using regex as follows
String toReplace = "'123'456'";
String regex = "'(?=.*')";
String replaced = toReplace.replaceAll(regex,"''");
System.out.println(replaced);
Here I get
''123''456'
How do I get
'123''456'
Thank you.
There is a pithy saying about regular expressions and two problems, but I'll skip that and suggest you simplify this by using a StringBuilder; find the index of both the first ' and the last ' in your input, then iterate between those indices looking for ' (and replacing with ''). Something like,
StringBuilder sb = new StringBuilder(toReplace);
int first = toReplace.indexOf("'"), last = toReplace.lastIndexOf("'");
if (first != last) {
for (int i = first + 1; i < last; i++) {
if (sb.charAt(i) == '\'') {
sb.insert(i, '\'');
i++;
}
}
}
toReplace = sb.toString();
int first = toReplace.indexOf("'") + 1;
int last = toReplace.lastIndexOf("'");
String afterReplace = toReplace.substring(0, first)
+ toReplace.substring( first,last ).replaceAll("'", "''")
+ toReplace.substring(last);
System.out.println(afterReplace);
With StringBuilder
String afterReplace = new StringBuilder()
.append(toReplace, 0, first)
.append(toReplace.substring(first, last).replaceAll("'", "''"))
.append(toReplace, last, toReplace.length())
.toString();
Or with String.format
String afterReplace = String.format("%s%s%s",
toReplace.substring(0, first),
toReplace.substring(first, last).replaceAll("'", "''"),
toReplace.substring(last));
Regex expression: (?<=')(. *)(?=')
It will help you to find out your result and then you can replace it.
This can be achieved with regex as well:
// String to be scanned to find the pattern.
String line = "'123'456'";
String pattern = "(?>^')(.*)(?>'$)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(1) );
String replaced = m.group(1).replaceAll("'","\"");
System.out.println("replaced value: " + replaced );
}else {
System.out.println("NO MATCH");
}
Related
I have String {a,b,c},{1,2,3}. How to extract to get like
String1 = a,b,c;
String2 = 1,2,3;
I have tried someting like this, but that does not work.
String result1 = str.substring(str.indexOf("{") + 1, str.indexOf("},"));
String result2 = str.substring(str.indexOf(",{") + 1, str.indexOf("}"));
There is an indexOf method that takes the index from which to search
String str = "{a,b,c},{1,2,3}";
int startingIndex = str.indexOf("{");
int closingIndex = str.indexOf("}");
String result1 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result1);
startingIndex = str.indexOf("{", closingIndex + 1);
closingIndex = str.indexOf("}", closingIndex + 1);
String result2 = str.substring(startingIndex + 1, closingIndex);
System.out.println(result2);
In the second block, we make the search start at closingIndex + 1 where closingIndex is the index of the last seen }.
You can use a regular expression for that e.g.
Matcher m = Pattern.compile("(?<=\\{).+?(?=\\})").matcher("{a,b,c},{1,2,3}");
while(m.find()){
System.out.println(m.group());
// a,b,c
// 1,2,3
}
One of the possible solutions for this task will be using Pattern class.
It should be a much more elegant solution for getting values between braces.
For matching the first group regex should be: \{([^}]*)\}.
Just add a separator between group , and repeat regex again. Now you can get results separately.
Here is code demo:
public class RegexDemo {
public static void main(String[] args) {
String str = "{a,b,c},{1,2,3}";
Pattern pattern = Pattern.compile("\\{([^}]*)\\},\\{([^}]*)\\}");
Matcher matcher = pattern.matcher(str);
String first = null;
String second = null;
if (matcher.find()) {
first = matcher.group(1);
second = matcher.group(2);
}
System.out.printf("First: %s\nSecond: %s\n", first, second);
}
}
Output:
First: a,b,c
Second: 1,2,3
I have a string "abcde-abc-db-tada_x12.12_999ZZZ_121121.333"
The result I want should be 999ZZZ
I have tried using:
private static String getValue(String myString) {
Pattern p = Pattern.compile("_(\\d+)_1");
Matcher m = p.matcher(myString);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
}
else {
System.out.println("not found");
}
}
If you want to continue with a regex based approach, then use the following pattern:
.*_([^_]+)_.*
This will greedily consume up to and including the second to last underscrore. Then it will consume and capture 9999ZZZ.
Code sample:
String name = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
Pattern p = Pattern.compile(".*_([^_]+)_.*");
Matcher m = p.matcher(name);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
} else {
System.out.println("not found");
}
Demo
Using String.split?
String given = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String [] splitted = given.split("_");
String result = splitted[splitted.length-2];
System.out.println(result);
Apart from split you can use substring as well:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String ss = (s.substring(0,s.lastIndexOf("_"))).substring((s.substring(0,s.lastIndexOf("_"))).lastIndexOf("_")+1);
System.out.println(ss);
OR,
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String arr[] = s.split("_");
System.out.println(arr[arr.length-2]);
The get text between the last two underscore characters, you first need to find the index of the last two underscore characters, which is very easy using lastIndexOf:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String r = null;
int idx1 = s.lastIndexOf('_');
if (idx1 != -1) {
int idx2 = s.lastIndexOf('_', idx1 - 1);
if (idx2 != -1)
r = s.substring(idx2 + 1, idx1);
}
System.out.println(r); // prints: 999ZZZ
This is faster than any solution using regex, including use of split.
As I misunderstood the logic from the code in question a bit with the first read and in the meantime there appeared some great answers with the use of regular expressions, this is my try with the use of some methods contained in String class (it introduces some variables just to make it more clear to read, it could be written in the shorter way of course) :
String s = "abcde-abc-db-ta__dax12.12_999ZZZ_121121.333";
int indexOfLastUnderscore = s.lastIndexOf("_");
int indexOfOneBeforeLastUnderscore = s.lastIndexOf("_", indexOfLastUnderscore - 1);
if(indexOfLastUnderscore != -1 && indexOfOneBeforeLastUnderscore != -1) {
String sub = s.substring(indexOfOneBeforeLastUnderscore + 1, indexOfLastUnderscore);
System.out.println(sub);
}
My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123
I am attempting to split a word from its punctuation:
So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.
Here is my code so far:
String inWord = "hello?";
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
String word = parts[0];
String punctuation = parts[1];
} else {
String word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
My problem is that I am getting error: cannot find symbol when I try and print out the word and the punctuation.
Thanks for help in advance
There are other things wrong with your code but your question was why you get the 'cannot find symbol' error.
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
The scope of a variable declaration like String word = ... is only the block (the pieces of code inside '{' and '}') that it's in. The variables word and punctuation don't exist in the scope in which you try to print them.
You need to declare your variables word and punctuation in the same scope (or an enclosing scope) of where you access them in your System.out.println
You made the following errors in your code.
1.Declare the string outside the if condition
2.inWord.contains(","+"?"+"."+"!"+";") this is equal to inword.contains(",?.!;") , so the condition will fail always and it goes to else condition
split() will not store the value based on which you split the string
eg
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
In this the value "-" can't be stored.Hope you understand what i'm trying to convey.
You could try with your custom contains function and StringTokenizer
as:
public class Test{
public static void main(String[] args) {
String inWord = "hello";
String[] wordAndPunctuation = null;
char[] punctuations =new char[]{',','?','.','!',';'};
StringTokenizer tokenizer = new StringTokenizer(inWord,new String(punctuations),true);
int i = 0;
if (Test.contains(inWord,punctuations)) {
while(tokenizer.hasMoreTokens()){
wordAndPunctuation = new String[tokenizer.countTokens()];
System.out.println(tokenizer.countTokens());
wordAndPunctuation[i] = tokenizer.nextToken();
i++;
}
}else{
System.out.println("No punctuation in "+inWord);
}
}
public static boolean contains(String str, char[] charArr){
System.out.println(Arrays.toString(charArr));
for(char c:charArr){
if(str.contains(String.valueOf(c)))
return true;
}
return false;
}
}
I would recommend parsing through the String and checking if the character is a punctuation method:
String sentence = "Hello? Is this Mrs. Doubtfire?"; // Example.
ArrayList<String> chunks = new ArrayList<>(); // Will store the "non-punctuated chunks"
ArrayList<Character> puncts = new ArrayList<>();// Will the punctuations in the "sentence"
char[] punctuations = {',','?','.','!',';'}; // Store punctuations here.
int lastIndex = 0;
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
for (char punctuation : punctuations) {
if (c == punctuation) {
chunks.add(sentence.substring(lastIndex, i).trim());
puncts.add(c);
lastIndex = i + 1;
}
}
}
System.out.println(chunks);
System.out.println(puncts);
Output:
[Hello, Is this Mrs, Doubtfire]
[?, ., ?]
And remember to import java.util.ArrayList!
Why don't you do this:
String s = "hello!";
Pattern p = Pattern.compile("(\\w+)?(\\W)");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println("Word: " + m.group(1) + " | Punctuation: " + m.group(2));
}
Group1 will contain the word and Group2 will contain the punctuation.
Demo : http://ideone.com/ljIZFW
I have ONE string field which is in format:
"TransactionID=30000001197169 ExecutionStatus=6
additionalCurrency=KMK
pin= 0000"
So they are not separated with some ; оr , they are not seperated even with one blank space.
I want to get value for Execution Status and put it in some field?
How to achieve this?
Thanks for help
This works. But I am not sure this is the most optimal.It just solves your problem.
String s = "TransactionID=30000001197169ExecutionStatus=6additionalCurrency=KMKpin=0000";
if(s!=null && s.contains("ExecutionStatus="))
{
String s1[] = s.split("ExecutionStatus=");
if(s1!=null && s1.length>1)
{
String line = s1[1];
String pattern = "[0-9]+";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Match");
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
}
}
In your example they are indeed seperated by blanks, but the following should be working without blanks, too. Assuming your String is stored in String arguments
String executionStatus;
String[] anArray = arguments.split("=");
for (int i; i < anArray.length; i++)
if (anArray[i].contains("ExecutionStatus")){
executionStatus = anArray[++i].replace("additionalCurrency","");
executionStatus = executionStatus.trim();
}
}
Check if it contains() ExecutionStatus=
If yes then split the string with ExecutionStatus=
Now take the Second string from array find the first occurance of non digit char and use substring()
Assuming all that white space is present in your string, this works.
String str = "\"TransactionID=30000001197169 ExecutionStatus=6\n" +
" additionalCurrency=\"KMK\"\n" +
" pin= \"0000\"\"";
int start = str.indexOf("ExecutionStatus=") + "ExecutionStatus=".length();
int status = 0;
if (start >= 0) {
String strStatus = str.substring(start, str.indexOf("additionalCurrency=") - 1);
try {
status = Integer.parseInt(strStatus.trim());
} catch (NumberFormatException e) {
}
}
At the risk of attracting "... and now you have two problems!" comments, this is probably easiest done with regexes (str is the String defined above):
Pattern p = Pattern.compile("ExecutionStatus\\s*=\\s*(\\d+)"); // Whitespace matching around equals for safety, capturing group around the digits of the status)
Matcher m = p.matcher(str);
String status = m.find() ? m.group(1) : null;