How to use REGEX to print :|: pattern after each string within delimeters - java

Suppose i have a string "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]" like this.
I am able to print [cat][dog][cow][monkey] from the above string.
How can i print something like this = [cat]:|:[dog]:|:[cow]:|:[monkey].
please help.
import java.util.regex.*;
public class RegexMain {
static final String PATTERN = "\\[([^]]+)\\]|\"[^\"]*\"";
static final Pattern CONTENT = Pattern.compile(PATTERN);
public static void main(String[] args) {
String test1 = "[cat] [] [dog] [cow] [] [] [monkey]";
Matcher match = CONTENT.matcher(test1);
while(match.find()) {
if(match.group(1).length() != 0) {
System.out.print( match.group().trim());
}
}
}
}

I am actually not sure what your string is exactly (you are using different ones in your explanation and code). Anyways you can try this :
public static void main(String[] args) {
String s = "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]";
System.out.println(s.replaceAll(":\\[\\]:\\|", ""));
}
O/P :
[cat]:|:[dog]:|:[cow]:|:[monkey]

how about
System.out.print( match.group().trim() + ":|:");

Related

grab last four digits approach after deleting non digits using regex

I'm getting the URL(http://localhost:8080/CompanyServices/api/creators/2173) shown below from a HTTP Response header and I want to get the id after the creators which is 2173.
So, I deleted all non digits as shown below and got the following result : 80802173.
Is it a good approach to get the last 4 digits from the above set of digits?
One thing is that, this part localhost:8080 could change depending upon the server I deploy my application so I'm wondering if I should just grab something after creators/ ? If yes, then what is the best way to go about it?
public class GetLastFourIDs {
public static void main(String args[]){
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
String replaceString=str.replaceAll("\\D+","");
System.out.println(replaceString);
}
}
You can use regex API e.g.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
Pattern pattern = Pattern.compile("(creators/\\d+)");
Matcher matcher = pattern.matcher(str);
int value = 0;
if (matcher.find()) {
// Get e.g. `creators/2173` and split it on `/` then parse the second value to int
value = Integer.parseInt(matcher.group().split("/")[1]);
}
System.out.println(value);
}
}
Output:
2173
Non-regex solution:
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
int index = str.indexOf("creators/");
int value = 0;
if (index != -1) {
value = Integer.parseInt(str.substring(index + "creators/".length()));
}
System.out.println(value);
}
}
Output:
2173
[Update]
Incorporating comment by Andreas as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
Pattern pattern = Pattern.compile("creators/(\\d+)");
Matcher matcher = pattern.matcher(str);
int value = 0;
if (matcher.find()) {
value = Integer.parseInt(matcher.group(1));
}
System.out.println(value);
}
}
Output:
2173

What is equivalent to .replaceSecond or .replaceThird?

In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and #. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and # to remove "smith"?
Our output now is alice+#john+smith#steve+oliver# but we want alice+luna#john+#steve+oliver#
public class Main {
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
System.out.println(newEmail);
}
}
You can find the second + like so:
int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);
(You need to handle the case that there aren't two +s to find, if necessary).
Then find the following #:
int at = email.indexOf('#', secondPlus);
Then stitch it back together:
String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);
or
String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();
Ideone demo
Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
newEmail = newEmail .replaceFirst("\\+.*?#", ""); //this replaces the second right? :)
newEmail = newEmail .replaceFirst("\\+.*?#", ""); // replace 3rd etc.
System.out.println(newEmail);
}
You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static String replaceNth(String str, int n, String regex, String replaceWith) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
n--;
if (n == 0) {
return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
}
}
return str;
}
public static void main(String args[]) {
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(replaceNth(email, 2, "\\+.*?#", ""));
}
}
I think it is better to encapsulate this logic into separate method, where String and group position are arguments.
private static final Pattern PATTERN = Pattern.compile("([^+#]+)#");
private static String removeSubstringGroup(String str, int pos) {
Matcher matcher = PATTERN.matcher(str);
while (matcher.find()) {
if (pos-- == 0)
return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
}
return str;
}
Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()
public static String removeFirst(String str) {
return removeSubstringGroup(str, 0);
}
public static String removeSecond(String str) {
return removeSubstringGroup(str, 1);
}
Demo:
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(email);
System.out.println(removeFirst(email));
System.out.println(removeSecond(email));
System.out.println(removeSubstringGroup(email, 2));
System.out.println(removeSubstringGroup(email, 3));
Output:
alice+luna#john+smith#steve+oliver#
alice+#john+smith#steve+oliver#
alice+luna#john+#steve+oliver#
alice+luna#john+smith#steve+#
alice+luna#john+smith#steve+oliver#
Ideone demo

String Regex for insert text based on searchstring

I have the following class.
public class TestStringRegex {
public static void main(String[] args) {
StringBuilder text = new StringBuilder("KALAKA");
String wordToFind = "KA";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println(match.end());
text=text.insert(match.end(),"INSERT");
}
System.out.println(text);
}
Expecting output to be KAINSERTLAKAINSERT.
But getting KAINSERTLAKA.
Is matcher/insert works on the length of input text?How to get desired output.
If you want to do it using matcher use the overloaded method with int i.e. matcher.find(index). For some reason mathcher.find() is not working as given in docs. If you are curious you need to debug the code.
Just say like below
int end = 0;
while (match.find(end)) {
end = match.end();
System.out.println(end);
text=text.insert(end,"INSERT");
}
Better way of doing the same will be
public static void main(String[] args) {
System.out.println("KALAKA".replaceAll("KA", "$0INSERT"));
}
That's all the code you need to write.
Use matcher.find(int startIndex) instead of find(). And update startIndex after each match. Full code:
public static void main(String[] args) {
StringBuilder text = new StringBuilder("KALAKA");
String wordToFind = "KA";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
int findIndex = 0;
while (match.find(findIndex)) {
int end = match.end();
findIndex = end;
text = text.insert(end, "INSERT");
}
System.out.println(text);
}
Each next find() starts at the end of previous match
This works fine..!!!
public static void main(String[] args) {
StringBuilder text = new StringBuilder("KALAKA");
String wordToFind = "KA";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
int end = 0;
while (match.find(end)) {
end = match.end();
text=text.insert(match.end(),"INSERT");
}
System.out.println(text);
}

replace string between first two occurrence of '&' chars

How can I replace string between first & and next & only:
public class Test02 {
public static void main(String[] args) {
String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
String x = xyz.replaceAll("&ram=.*&", "&ram=8 gb&");
System.out.println(x);
}
}
my input - &axy=asdsd&ram=2 gb4 gb&asd=sdsd&
my output - &axy=asdsd&ram=8 gb&
but I want- &axy=asdsd&ram=8 gb&asd=sdsd&
only want to change middle part.
I am making a search filter. If any API for building query exists I would love to know.
Thanks bobble,
this worked... '.?' instead of '.' ..
public class Test02 {
public static void main(String[] args) {
String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
String x = xyz.replaceAll("(&ram=.*?)&", "&ram=8 gb&");
System.out.println(x);
}
}
now out put-- &axy=asdsd&ram=8 gb&asd=sdsd&
You can use the split method on your String to break it into its tokens with a given delimiter. Then just replace whatever index you want with the new desired value.
Something like this (not tested)
String text = "A&B&C";
String delim = "&";
String[] elements = text.split(delim);
elements[0]= "D";
String result = "";
for (String token : elements) {
result += token + delim;
}
System.out.println(result.substring(0, result.length() - delim.length())); // "D&B&C"
public static void main(String[] args) {
String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
int firstAndPosition =xyz.indexOf('&',1);
int secondAndPosition =xyz.indexOf('&',firstAndPosition+1);
String stringToReplace = xyz.substring(firstAndPosition, secondAndPosition +1);
//The do your stuff
String x = xyz.replaceAll(stringToReplace, "&ram=8 gb&");
System.out.println(x);
}
}
You need to use a negated character class [^&] matching any character but a & with a * quantifier (zero or more occurrences) and leverage String#replaceFirst() method to only perform one replacement:
String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
String x = xyz.replaceFirst("&ram=[^&]*&", "&ram=8 gb&");
System.out.println(x);
// => &axy=asdsd&ram=8 gb&asd=sdsd&
See IDEONE demo

Java Split a String with coma or 0(zero) followed by a whitespace

If I have a string, e.g.
s = "david,marko,rita,0 megan,0 vivian,law";
I need split this string into
david
marko
rita
megan
vivian
law
I am trying with
String arr[] = s.split("[,\\s]");
but didnĀ“t work. Any suggestions?
You could use this expression:
String arr[] = s.split(",0?\\s*");
Or maybe even:
String arr[] = s.split("[,0\\s]+");
Which one you want is unclear from the example.
Your regex is : "(,0 |,)"
So try this code :
public static void main(String[] args){
String s = "david,marko,rita,0 megan,0 vivian,law";
String[] ss = s.split("(,0 |,)");
for (int i = 0; i < ss.length; i++) {
String string = ss[i];
System.out.println(string);
}
}
Just an advice
Rather then splitting with multiple values try this
import java.util.*;
class test {
public static void main(String[] args) {
String s = "david,marko,rita,0 megan,0 vivian,law";
System.out.println(Arrays.toString(s.replace("0","").replace(" ","").split(",")));
}
}
You can try this:
public class SplitTest {
public static void main(String[] args) {
String inputString = "david,marko,rita,0 megan,0 vivian,law";
String splits[] = inputString.split(",0?\\s*");
for (String split : splits) {
System.out.println(split);
}
}
}
String[] arr = s.split(",(0\\s+)*");
The regex splits on a comma followed optionally by a 0 and one or more spaces.
public static void main(String[] args) {
String s = "da0vid,marko,rita,0 megan,0 vivian,law";
String[] arr = s.split(",(0\\s+)*");
for (int i = 0; i < arr.length; i++)
System.out.println("'"+arr[i]+"'");
}
=>
'da0vid'
'marko'
'rita'
'megan'
'vivian'
'law'

Categories