java regular expression find and replace multiple [duplicate] - java

This question already has answers here:
Regular Expression for matching parentheses
(5 answers)
Closed 6 years ago.
I am trying to replace following code using regex in my code base.
if(StringFunctions.isNullOrEmpty(employee.getName())){
//java code
}
New code should be:
If(StringUtils.isEmpty(StringUtils.trim(employee.getName()))){
//java code
}
I have written following code to perform the update.
String regEx = "StringFunctions.isNullOrEmpty(.*)";
String replacement = "StringUtils.isEmpty(StringUtils.trim$1)";
textFromFile.replaceAll(regEx,pattern);
output is:
If(StringUtils.isEmpty(StringUtils.trim(employee.getName())){)
//java code
}
what is wrong in my code??? please help me

In regex () is the capturing group. Your regex pattern is incorrect because where you meant to put literal brackets, you have instead only put a capturing group.
The correct regex pattern is:
"StringFunctions.isNullOrEmpty\\((.+)\\)"
\\((.+)\\) means match a literal open bracket followed by (and capture) 1 or more of any character, followed by a literal closing bracket.
Testing:
String textFromFile = "if(StringFunctions.isNullOrEmpty(employee.getName())){}";
String regEx = "StringFunctions.isNullOrEmpty\\((.+)\\)";
String replacement = "StringUtils.isEmpty(StringUtils.trim($1))";
String output = textFromFile.replaceAll(regEx,replacement);
System.out.println(output);
Input:
if(StringFunctions.isNullOrEmpty(employee.getName())){}
Output:
if(StringUtils.isEmpty(StringUtils.trim(employee.getName()))){}

Related

How to extract sub string by matching the known set of keyword(s) [duplicate]

This question already has answers here:
Regex match one of two words
(2 answers)
Closed 2 years ago.
Trying to extract substring after a particular code for example
String sample1 = "/ASDF/096/GHJKL/WER/WER/dv/7906/CODEM/TEAR1331927498xxxxxx/YUII/OPL";
String sample2 = "/CODEM/TEAR1331927498xxxxxx";
String regExpresssion = "[/CODEM/]{6}(^[a-zA-Z0-9|\\s])?";
final Pattern pattern = Pattern.compile(regExpresssion);
final Matcher matcher = pattern.matcher(sample1);
if (matcher.find()) {
String subStringOut = sample1.substring(matcher.end());
}
subStringOut for sample 1 > TEAR1331927498xxxxxx/YUII/OPL
subStringOut for sample 2 > TEAR1331927498xxxxxx
above code is working fine but now I need to add one more identifier '/CODER/' in regex expression for below sample
String sample3 = "/ASDF/096/GHJKL/WER/WER/dv/7906/CODER/TEAR1331927498xxxxxx/YUII/OPL";
I have tried
String regExpresssion = "[/CODEM/|/CODER/]{6}(^[a-zA-Z0-9|\\s])?";
but it is not working. Any suggestions guys?
Thanks!!
try replacing [/CODEM/|/CODER/]{6} with /CODE[RM]/
I think you meant to match the entire phrase /CODEM/ or /CODER/ but because of the way you wrote it you were accepting any sequence of any of those characters 6 characters long. I'm not entirely sure though. The Brackets represent a "character class" and they only match a single character, if you want to match multiple in a row you use parentheses. Also the second part does not make sense to me because the exponent sign is in the middle of the phrase, and in that context it matches the beginning of a line.
Just need single look behind assersun
Try (?<=/CODE[MR]/).*
PCRE demo
but works for Java in this case

String#replaceAll() method not replacing for $ (dollar) [duplicate]

This question already has answers here:
Java regular expressions and dollar sign
(5 answers)
Closed 6 years ago.
I've tried built-in method String#replaceAll() to replace all "$" from my String content. But it's not working.
String ss = "HELLO_$_JAVA";
System.out.println(ss.indexOf("$"));
System.out.println(ss);
ss = ss.replaceAll("$", "");
System.out.println(ss);// 'HELLO__JAVA' is expected
OUTPUT:
6
HELLO_$_JAVA
HELLO_$_JAVA
Expected output:
6
HELLO_$_JAVA
HELLO__JAVA
EDIT:
Although Java regular expressions and dollar sign covers the answer, but still my question may be helpful for someone who is facing same problem when using String#replaceAll().
And
Difference between String replace() and replaceAll() also may be helpful.
Two possible solution of that question is
ss = ss.replace("$", "");
OR
ss = ss.replaceAll("\\$", "");
The first parameter of the replaceAll method takes a regular expression, not a literal string, and $ has a special meaning in regular expressions.
You need to escape the $ by putting a backslash in front of it; and the backslash needs to be double because it has a special meaning in Java string literals.
ss = ss.replaceAll("\\$", "");
String.replaceAll is for regular expressions. '$' is a special character in regular expressions.
If you are not trying to use regular expressions, use String.replace, NOT String.replaceAll.
May be not the best way but a work around,
String parts[] = ss.split("\\$");
Then concat each of them
String output = "";
for(String each:parts){
output=output+each;
}
Then you have your replaced string in output

REgular Expression using Java [duplicate]

This question already has answers here:
Java string split with "." (dot) [duplicate]
(4 answers)
Closed 8 years ago.
I am Using Regular Expression to break the string, I am trying to break the string but In reqular Expressions I am missing some format. Can any one please let me know where i went wrong.
String betweenstring="['Sheet 1$'].[DEPTNO] AS [DEPTNO]";
System.out.println("betweenstring: "+betweenstring);
Pattern pattern = Pattern.compile("\\w+[.]\\w+");
Matcher matchers=pattern.matcher(betweenstring);
while(matchers.find())
{
String filtereddata=matchers.group(0);
System.out.println("filtereddata: "+filtereddata);
}
I need to break like this:
['Sheet 1$']
[DEPTNO] AS [DEPTNO]
Given your very specific input, this regex works.
([\w\[\]' $]+)\.([\w\[\]' $]+)
Capture group one is before the period, capture group 2, after. To escape this for a Java string:
Pattern pattern = Pattern.compile("([\\w\\[\\]' $]+(\\.*[\\w\\[\\]' $]+)");
However, it would be much easier to split the string on the literal dot, if this is what you are trying to achieve:
String[] pieces = between.split("\\.");
System.out.println(pieces[0]);
System.out.println(pieces[1]);
Output:
['Sheet 1$']
[DEPTNO] AS [DEPTNO]

How to write a regex for words like [[gold]] or [[Archimedes]] [duplicate]

This question already has answers here:
java regular expression to extract content within square brackets
(3 answers)
Closed 8 years ago.
I have an array of strings. I am checking for the following pattern in each element of the array: [[some word]].
The element should start with two square brackets and end with 2 square brackets with a word or a sentence in between them.
I also need to extract the string "some word" from [[some word]]. I am unable to figure out the regular expressions in Java. They appear to be very different from scripting language like PHP.
Eg. If I encounter [[this is an example]] while traversing the array, I should output "this is an example". This should be done for all strings enclosed in double square brackets.
The following code:
String input = "How to write a regex for words like [[gold]] or [[Archimedes]] in JAVA";
String regex = "\\[\\[(.*?)\\]\\]";
Matcher matcher = Pattern.compile(regex).matcher(input);
int idx=0;
while(matcher.find(idx)){
String match = matcher.group(1);
System.out.println(match);
idx = matcher.end();
}
prints:
gold
Archimedes
The actual regex (without escaped \) is:
\[\[(.*?)\]\]
I believe this regex should work for you:
"(?s)\\[\\[(.*?)\\]\\]"
This will also grab multi line sentence between [[ and ]] because of use of (?s) (DOTALL)
\\[\\[([^]]*)\\]\\] can be used as a slight variation on #anubhava's answer. As the comments here point out, it won't catch [[a]b]], but I couldn't tell whether that was part of your requirement or not.

Java regex error Illegal repetition [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Flex RegExp to Java RegExp
I don't know why is it not working.. I'm using java..
...
String patternString = "([^{}]*{[^{}]+}[^{}])*";
Pattern p = Pattern.compile(patternString);
...
The error that i receive is:
Illegal repetition near index 4
([^{}]*{[^{}]+}[^{}]*)
You need to escape the literal braces unless they're inside a character class:
String patternString = "([^{}]*\\{[^{}]+\\}[^{}])*";
Most other regex flavors can recognize when braces are not being used as a repetition operator (as in [0-9]{1,3}) and therefore will parse the regex correctly. But Java is insistent on having these braces escaped.

Categories

Resources