Given this text:
$F{abc} and $F{def}
I need to get
abc and def
For that, I would use this regex to find the values \$F\{\w*\} but I need to get what's represented by w*:
str.replaceAll("\\$F\{\\w*\\}", "??" );
Is this doable with a Java function or I need to write the routine?
You can capture the text in a group:
str = str.replaceAll("\\$F\\{(\\w*)}", "$1");
Update
I didn't read your question completely. Thanks to The fourth bird for pointing it out. Given below is the code for the expected output, abc and def
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("\\$F\\{(\\w*)\\}", "$1"));
}
}
Output:
abc and def
All you need to do is to replace the given string with the capturing group(1). The explanation in the original answer is still valid for this update.
Original answer:
You can use the regex, (\$F\{)(\w*)(\}) and replace the capturing group(2) with ?? and preserve the capturing group(1) and the capturing group(3) as shown below:
public class Main {
public static void main(String[] args) {
String str = "$F{abc} and $F{def}";
System.out.println(str.replaceAll("(\\$F\\{)(\\w*)(\\})", "$1??$3"));
}
}
Output:
$F{??} and $F{??}
Check this for an illustration of all the capturing groups in the regex, (\$F\{)(\w*)(\}).
One way is to use the regex (\\$F\\{)|(\\}) you can both remove the "$F{" and "}" parts using replaceAll():
String str = "$F{abc} and $F{def}";
str = str.replaceAll("(\\$F\\{)|(\\})", "");
About regex:
(\\$F\\{) : 1. group "$F{"
| : OR
(\\}) : 2. group "}"
Other way is to use a capture group reference in the replacement parameter. $1 stands for the capture group (\\w*) that corresponds to abc and def
String str = "$F{abc} and $F{def}";
str = str.replaceAll("\\$F\\{(\\w*)\\}", "$1" );
System.out.println(str);
Output:
abc and def
Related
I have a String to be checked for regex :
"field":"Testing, for something \"and something\""
which I want to pattern match and replace with :
"field":"SAFE"
For this, I am trying to pattern match and capture till the last inverted commas. I have tried the following regex, but its not matching :
Pattern p = Pattern.compile("\"field\":\".*?(?!\\\")\"");
New to regex, can anyone suggest what I might be doing wrong? Thanks!
EDIT :
I guess the question was not clear. Apologies. The above is not the end of the string. It can contain more fields in succession :
"field":"Testing, for something \"and something\"", "new_field":"blahblah", ...
output should be :
"field":"SAFE", "new_field":"blahblah", ...
You can do it as follows:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\"";
str = str.replaceAll("(\"field\":).*", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE"
Explanation:
(\"field\":) is the first capturing group
.* specifies all characters
$1 specifies the first capturing group
Update:
Writing this update based on the clarification from OP.
You can use positive lookahead for comma as shown below:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\", \"new_field\":\"blahblah\"";
str = str.replaceAll("(\"field\":).*(?=,)", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE", "new_field":"blahblah"
Here is an example.
$str = '"field":"Testing, for something \"and something\""';
echo preg_replace('/(\"field\":\")(.*)(\")/i', "$1SAFE$3", $str);
Regex is tested: here.
I have a String "abcabc" and I want to split it and print like this:
abc
abc
Code definition for string:
String word = "abcabc";
We can try using String#replaceAll for a one line option:
String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);
This prints:
abc
abc
The idea is to apply a pattern to the entire string which matches and captures some quantity, which is then followed by the same quantity to the end. Here is the pattern explained as executed against your exact input abcabc:
(.*) match 'abc'
(?=\1$) then lookahead and assert that what follows to the end of the string
is exactly another 'abc'
.* consume, but do not match, the remainder of the input (which must be 'abc')
Then, we replace with $1\n$1, which is the first capture group twice, separated by a newline.
The string split():
public class Split {
public static void main(String args[])
{
String str = "ABC#ABC";
String[] arrOfStr = str.split("#", 5);
for (String a : arrOfStr)
System.out.println(a);
}
}
This Also Prints :
ABC
ABC
class Stack{
public static void main(String $[]){
foo();
}
public static void foo(){
String in="abc abc abc";//spaces are used as seperator.
String res[]=in.split(" ");//Returns an Array of String
for(int i=0;i<res.length;i++)
System.out.println(res[i]);
}
}
output:
abc
abc
abc
Maybe someone could help me. I'm trying to include within a java code a regex to match all strings except the ZZ78. I'd like to know what it's missing in the regex I have.
The input string is str = "ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78"
and I'm trying with this regex (?:(?![ZZF8]).)* but if you test in http://regexpal.com/
this regex against the string, you'll see that is not working completely.
str = new String ("ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78");
Pattern pattern = Pattern.compile("(?:(?![ZZ78]).)*");
the matched strings should be
ab57cd
efghZZ7ij#klm
noCODpqr
stuvw27z#xyz
Update:
Hello Avinash Raj and Chthonic Project. Thanks so much for your help and solutions provided.
I originally thougth in split method, but I was trying to avoid get empty strings as result
when for example the delimiter string is at the beginning or at the end of the main string.
Then, I thought that a regex could help me to extract all except "ZZ78", avoiding in this way
empty results in the output.
Below I show the code using split method (Chthonic´s) and regex (Avinash´s) both produce empty
string if the commented "if()" conditions are not used.
Does the use of those "if()" are the only way to not print empty strings? or could be the regex
tweaked a little bit to match not empty strings?
This is the code I have tested so far:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
System.out.println("########### Matches with Split ###########");
String str = "ZZ78ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
for (String s : str.split("ZZ78")) {
//if ( !s.isEmpty() ) {
System.out.println("This is a match <<" + s + ">>");
//}
}
System.out.println("##########################################");
System.out.println("########### Matches with Regex ###########");
String s = "ZZ78ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
Pattern regex = Pattern.compile("((?:(?!ZZ78).)*)(ZZ78|$)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
//if ( !matcher.group(1).isEmpty() ) {
System.out.println("This is a match <<" + matcher.group(1) + ">>");
//}
}
}
}
**and the output (without use the "if()´s"):**
########### Matches with Split ###########
This is a match <<>>
This is a match <<ab57cd>>
This is a match <<efghZZ7ij#klm>>
This is a match <<noCODpqr>>
This is a match <<stuvw27z#xyz>>
##########################################
########### Matches with Regex ###########
This is a match <<>>
This is a match <<ab57cd>>
This is a match <<efghZZ7ij#klm>>
This is a match <<noCODpqr>>
This is a match <<stuvw27z#xyz>>
This is a match <<>>
Thanks for help so far.
Thanks in advance
Update #2:
Excellent both of your answers and solutions. Now it works very nice. This is the final code I've tested with both solutions.
Many thanks again.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
System.out.println("########### Matches with Split ###########");
String str = "ZZ78ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
Arrays.stream(str.split("ZZ78")).filter(s -> !s.isEmpty()).forEach(System.out::println);
System.out.println("##########################################");
System.out.println("########### Matches with Regex ###########");
String s = "ZZ78ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
Pattern regex = Pattern.compile("((?:(?!ZZ78).)*)(ZZ78|$)");
Matcher matcher = regex.matcher(s);
ArrayList<String> allMatches = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
while(matcher.find()){
allMatches.add(matcher.group(1));
}
for (String s1 : allMatches)
if (!s1.equals(""))
list.add(s1);
System.out.println(list);
}
}
And output:
########### Matches with Split ###########
ab57cd
efghZZ7ij#klm
noCODpqr
stuvw27z#xyz
##########################################
########### Matches with Regex ###########
[ab57cd, efghZZ7ij#klm, noCODpqr, stuvw27z#xyz]
The easiest way to do this is as follows:
public static void main(String[] args) {
String str = "ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
for (String s : str.split("ZZ78"))
System.out.println(s);
}
The output, as expected, is:
ab57cd
efghZZ7ij#klm
noCODpqr
stuvw27z#xyz
If the pattern used to split the string is at the beginning (i.e. "ZZ78" in your example code), the first element returned will be an empty string, as you have already noted. To avoid that, all you need to do is filter the array. This is essentially the same as putting an if, but you can avoid the extra condition line this way. I would do this as follows (in Java 8):
String test_str = ...; // whatever string you want to test it with
Arrays.stream(str.split("ZZ78")).filter(s -> !s.isEmpty()).foreach(System.out::println);
You must need to remove the character class since [ZZ78] matches a single charcater from the given list. (?:(?!ZZ78).)* alone won't give the match you want. Consider this ab57cdZZ78 as an input string. At first this (?:(?!ZZ78).)* matches the string ab57cd, next it tries to match the following Z and check the condition (?!ZZ78) which means match any character but not of ZZ78. So it failes to match the following Z, next the regex engine moves on to the next character Z and checks this (?!ZZ78) condition. Because of the second Z isn't followed by Z78, this Z got matched by the regex engine.
String s = "ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
Pattern regex = Pattern.compile("((?:(?!ZZ78).)*)(ZZ78|$)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Output:
ab57cd
efghZZ7ij#klm
noCODpqr
stuvw27z#xyz
Explanation:
((?:(?!ZZ78).)*) Capture any character but not of ZZ78 zero or more times.
(ZZ78|$) And also capture the following ZZ78 or the end of the line anchor into group 2.
Group index 1 contains single or group of characters other than ZZ78
Update:
String s = "ZZ78ab57cdZZ78efghZZ7ij#klmZZ78noCODpqrZZ78stuvw27z#xyzZZ78";
Pattern regex = Pattern.compile("((?:(?!ZZ78).)*)(ZZ78|$)");
Matcher matcher = regex.matcher(s);
ArrayList<String> allMatches = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
while(matcher.find()){
allMatches.add(matcher.group(1));
}
for (String s1 : allMatches)
if (!s1.equals(""))
list.add(s1);
System.out.println(list);
Output:
[ab57cd, efghZZ7ij#klm, noCODpqr, stuvw27z#xyz]
I have string, and I want to replace one of its character with backslash \
I tried the following, but no luck.
engData.replace("'t", "\\'t")
and
engData = engData.replace("'t", String.copyValueOf(new char[]{'\\', 't'}));
INPUT : "can't"
EXPECTED OUTPUT : "can\'t"
Any idea how to do this?
Try this..
String s = "can't";
s = s.replaceAll("'","\\\\'");
System.out.println(s);
out put :
can\'t
This will replace every ' occurences with \' in your string.
Try like this
engData.replace("'", "\\\'");
INPUT : can't
EXPECTED OUTPUT : can\'t
String is immutable in Java. You need to assign back the modified string to itself.
engData = engData.replace("'t", "\\'t"); // assign the modified string back.
This is possible with regex:
engData = engData.replaceAll("('t)","\\\\$1");
The ( and ) specify a group. The 't will match any string containing 't. Finally, the second part replaced such a string with a backslash character: \\\\ (four because this), and the first group: $1. Thus you are replacing any substring 't with \'t
The same thing is possible without regex, what you tried (see this for output):
engData = engData.replace("'t","\\'t"); //note the assignment; Strings are immutable
See String.replace(CharSequence, CharSequence)
For String instances you can use, str.replaceAll() will return a new String with the changes requested:
String str = "./";
String s_modified = s.replaceAll("\\./", "");
The following works for me:
class Foobar {
public static void main(String[] args) {
System.err.println("asd\\'t".replaceAll("\\'t", "\\\'t"));
}
}
Example
input: abc def abc abc pqr
I want to to replace abc at third position with xyz.
output: abc gef abc xyz pqr
Thanks in advance
One way to do this would be to use.
String[] mySplitStrings = null;
String.Split(" ");
mySplitString[3] = "xyz";
And then rejoin the string, its not the best way to do it but it works, you could put the whole process into a function like.
string ReplaceStringInstance(Seperator, Replacement)
{
// Do Stuff
}
Group the three segments, that are the part before the replaced string, the replaced string and the rest and assemble the prefix, the replacement and the suffix:
String pattern = String.format("^(.*?%1$s.*?%1$s.*?)(%1$s)(.*)$", "abc");
String result = input.replaceAll(pattern, "$1xyz$3");
This solution assumes that the whole input is one line. If you have multiline input you'll have to replace the dots as they don't match line separators.
There's plenty of ways to do this, but here's one. It assumes that the groups of letters will be separated by spaces, and looks for the 3rd 'abc' block. It then does a single replace to replace that with 'xyz'.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class main {
private static String INPUT = "abc def abc abc pqr";
private static String REGEX = "((?:abc\\ ).*?(?:abc\\ ).*?)(abc\\ )";
private static String REPLACE = "$1xyz ";
public static void main(String[] args) {
System.out.println("Input: " + INPUT);
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
INPUT = m.replaceFirst(REPLACE);
System.out.println("Output: " + INPUT);
}
}