Java Regular Expression for 1 = 1

I need to look for a java regex template that finds an input string in the format 1 = 1, where the prefix "=" should have the same number of digits with a suffix. Also here, both the prefix and suffix values ​​should be the same as 1 = 1, 11 = 11, 223 = 223. Values ​​such as 1 = 2, 3 = 22, 33 = 22 should not match the pattern

Can we have a common template to comply with the above rules.

+7
java regex
source share
3 answers

Use the back link:

(\d+)=\1\b 

of course in java you need to avoid backslashes:

 "(\\d+)=\\1\\b" 
+9
source share

You can also check without regex.

  String exp="lhs=rhs"; if(exp.split("=")[0].equals(exp.split("=")[1])){ System.out.println("true"); }else{ System.out.println("false"); } 
+3
source share

You can use capture groups and backlinks :

 ^(\\d+)=\\1$ 

[Labels should prevent something else]

Perhaps a more convincing expression would look like this:

 ^\\s*(\\d+)\\s*=\\s*\\1\\s*$ 

What takes ignores possible spaces that might otherwise not work as expected. Of course, now it depends on whether you say, for example, that 1 =1 is a valid input string.


A more general expression might be:

 ^\\s*(.+?)\\s*=\\s*\\1\\s*$ 

Where you can compare any line before the equal sign. .+? matches any character before the equal sign.

+1
source share

All Articles