Hi
Is there any way to make sure that a certain regex is valid ?
I give textfield with regex for user, but if user is filling "*" for example the program crash.
Printable View
Hi
Is there any way to make sure that a certain regex is valid ?
I give textfield with regex for user, but if user is filling "*" for example the program crash.
Hi
Check like this.I have demonstrated with the small piece of code.Just it checks the text for "*".if it finds then it prints invalid else valid.
Go thru the below link for better understanding.
Pattern (Java 2 Platform SE v1.4.2))
import java.util.regex.*;
class LogIn
{
public static void main(String args[])
{
String input = "sun*com";
//Checks for the string which is having * or not
Pattern p = Pattern.compile("\\*");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("invalid string.");
else
System.err.println("valid string");
//Checks for email addresses that start with
//www. and prints a message if it does.
}//main
}//class
Sorry but you miss-understand me
I have text , tested text, let call it.
I also have a regex string , which the user provides.
if the text isand the user put in the regexQuote:
abc1234
then we have a matchQuote:
abc[/d]*
but if user put in regex- no match.Quote:
abcd+
The problem is what the user put "bad regex" ?which is one example , and I'm sure there are more. ( the * in the begining makes it "bad" regex )Quote:
*abc*
on the function
I get these errors:Code:text.matches(regexStr);
Quote:
Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*[dD]*
^
at java.util.regex.Pattern.error(Pattern.java:1650)
at java.util.regex.Pattern.sequence(Pattern.java:1787 )
at java.util.regex.Pattern.expr(Pattern.java:1687)
at java.util.regex.Pattern.compile(Pattern.java:1397)
at java.util.regex.Pattern.<init>(Pattern.java:1124)
at java.util.regex.Pattern.compile(Pattern.java:817)
at java.util.regex.Pattern.matches(Pattern.java:919)
at java.lang.String.matches(String.java:1921)
Looking through java.util.regex I couldn't find anything which tested if the regular expression was well formed. The only suggestion I can give is to use a try-catch.
That does seem like it would be a useful method to incorporate into the Pattern class.
Mr. Beans
nice, try-catch seem to be the simplest solution. thanks
How can I marked this topic as "Solved" ?