Delete intersection of multiple regexes?

Pattern[] a =new Pattern[2]; a[0] = Pattern.compile("[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d"); a[1] = Pattern.compile("Rs[.]?\\s*[\\d,]*[.]?\\d*\\d"); 

Ex: Rs.150 determined by a[1] , and 150 is determined by a[0] . How to remove such intersections, and let it detect only a[1] , but not a[0] ?

+4
source share
3 answers

You can use the operator | inside your regular expression. Then call the Matcher # group (int) method to see which template your input refers to. This method returns null if the matching group is empty.

Code example

 public static void main(String[] args) { // Build regexp final String MONEY_REGEX = "[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d"; final String RS_REGEX = "Rs[.]?\\s*[\\d,]*[.]?\\d*\\d"; // Separate them with '|' operator and wrap them in two distinct matching groups final String MONEY_OR_RS = String.format("(%s)|(%s)", MONEY_REGEX, RS_REGEX); // Prepare some sample inputs String[] inputs = new String[] { "$100", "Rs.150", "foo" }; Pattern p = Pattern.compile(MONEY_OR_RS); // Test each inputs Matcher m = null; for (String input : inputs) { if (m == null) { m = p.matcher(input); } else { m.reset(input); } if (m.matches()) { System.out.println(String.format("m.group(0) => %s\nm.group(1) => %s\n", m.group(1), m.group(2))); } else { System.out.println(input + " doesn't match regexp."); } } } 

Output

  m.group (0) => $ 100
     m.group (1) => null

     m.group (0) => null
     m.group (1) => Rs. 150

     foo doesn't match regexp.
0
source

Use an initial test to switch between expressions. How fast and / or smart this initial test is up to you.

In this case, you can do something like:

 if (input.startsWith("Rs.") && a[1].matcher(input).matches()) { return true; } 

and put it in front of your test method.

Just using regular regular expressions before an array can also help, of course.

0
source

Description

Use a negative appearance to match the format a[1] rs.150 , while at the same time preventing the format a[0] 150 .

General expression: (?! the a[0] regex goes here ) followed by the a[1] expression

Status of the main regular expression: (?![$£€]?\s*\d*[\.]?[pP]?\d*\d)Rs[.]?\s*[\d,]*[.]?\d*\d

shielded for java: (?![$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d)Rs[.]?\\s*[\\d,]*[.]?\\d*\\d

enter image description here

0
source

Source: https://habr.com/ru/post/1486587/


All Articles