Java regex error Illegal repetition [duplicate] - java

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.

Related

This pattern matches for input 123456789.2.2.2 , which it should not [duplicate]

This question already has answers here:
Java RegEx meta character (.) and ordinary dot?
(9 answers)
Closed 6 years ago.
I am trying to solve following task:
Match the pattern abc.def.ghi.jkl, where each variable a,b,c,d,e,f,g,h,i,j,k,l can be any single character except the newline.
For above question I am matching the input to regex :
"([^\\n]{3}(.)){3}([^\\n]{3})"
// this is the regex pattern I am using currently
What am I doing wrong? Please help me correct the above regex so that it does not match the incorrect input I have provided in the title. Currently it matches to it somehow. Although I have provided 3 it is apparently matching to more than 3 characters.
. has a special meaning in regular expression patterns.
If you want to get a "simple dot", you need to quote/escape it (as "\\.").
And that special meaning is (under normal configuration) "any character except line breaks", which exactly matches your other condition, so you can simplify this to
"(...)\\.(...)\\.(...)\\.(...)"

java regular expression find and replace multiple [duplicate]

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()))){}

using if statment with regular expressions to know if String contains specified characters or not in java [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 7 years ago.
i have made this code and i don't know what is the problem with it, why the output print " f "??? even that the string contains the specified characters in the regex
String s="x^2+x-20";
Pattern pattern =
Pattern.compile("([+-][0-9]*)(([a-z A-Z])\\^2)"); //regex
Matcher matcher = pattern.matcher(s);
if(matcher.matches()){
System.out.println("t");
} else {
System.out.println("f");}
Your regex makes [+-] not an optional match but rather required. Use the following:
"([+-]?[0-9]*)(([a-z A-Z])\\^2)" // java syntax
Or as a regex without any java escaping:
([+-]?[0-9]?)(([a-z A-Z])\^2)
Also use Matcher.find rather than Matcher.match to find matches that are not the entire string.

Can't escape a closing parenthesis in Java? [duplicate]

This question already has answers here:
Java doesn't work with regex \s, says: invalid escape sequence
(3 answers)
Closed 2 years ago.
I have a very long regular expression that seems to be having issues, but only when imported from a text file. I've narrowed it down to the following section (shown here as a literal String):
"(?i)(?<!\\w)\\w{2,3}(?=\\))"
As you can see, near the end, I am trying to escape a closing parenthesis for a lookahead. Now, if this is hard-coded, like:
Pattern myPattern = Pattern.compile("(?i)(?<!\\w)\\w{2,3}(?=\\))");
It works completely as expected. If, however, I read it from a text file, like:
File patternFile = new File("patterns.txt");
List<String> patternText = FileUtils.readLines(patternFile);
String ucText = patternText.get(0).trim();
Pattern myPattern = Pattern.compile(ucText);
Then I get the error message:
Exception in thread "Thread-4" java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 25
(?i)(?<!\\w)\\w{2,3}(?=\\))
^
So, why is this happening? Why is escaping a closing parenthesis legal when hard-coded, but not when reading from a text file?
You're writing a Java string literal. \) is not a legal escape code for Java string literals.
You need to escape every backslash with \\ to create a string with a single backslash for the regex.
only when imported from a text file
You have to print that to the console.
If it prints out (?i)(?<!\w)\w{2,3}(?=\)) its ok,
if it prints out with it double escaped, you have to un-escape those
A good way to un-escape the escape character is do a global find/replace
(this is %90 of the parsing)
Find "(?x)\\\\ \\\\"
Replace "\\\\"
Un-escape non-escapes is a relative approach.
And it depends upon the character and the substitution,
or no action on either. This is mostly language specific,
but you can roll your own. For this, the basic's are ...
Find "(?xs)\\\\ (.)"
Replace roll your own"

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]

Categories

Resources