Search code examples
oracle11gpattern-matchingregexp-like

To check if specified pattern is repeating through the entire length of string


I am trying to match a pattern which is like '12345@5.6;12345@45;12345@0.5'.I am trying to Oracle(11g) REGEXP_LIKE function to do that. Here is my code-

SET SERVEROUTPUT ON;

Begin

if regexp_like( TRIM('12345@5.6;12345@45;12345@0.5'),'[^\d+@((\d+.\d{0,4})|(\d+));$]+')

then
dbms_output.put_line('yes');
else 
dbms_output.put_line('No');
end if;

end;

For the above code output is 'Yes' which is what i wanted.But this code is also returning 'yes' for pattern like '12345@5.6,12345@45;12345@0.5'(instead of semi colon I specified comma after '5.6').

It is basically checking for the pattern but if it finds at least one pattern of this kind this is returning true and not checking for the remaining string to make sure everything is in the pattern.

I want only patterns of the specified kind in the entire length of the string.If something is out of pattern I need to return 'No'.

Another eg:- For suppose there is a string 'abc;abc;abc' I want to check if pattern 'abc' not only exists in the string but also repeats itself through entire string. That means code should return false for strings like 'abc;bca;def' and should return true only for 'abc;abc;abc'.

To be clear,I just want to check if specified pattern is repeating through the entire length of string else I want to return 'No',not just see at least one exists and return true and I do not know how many times this pattern exist.

Hope I am clear,Please help.Thank you.


Solution

  • You may use

    '^[0-9]+@[0-9]+(\.[0-9]{0,4})?(;[0-9]+@[0-9]+(\.[0-9]{0,4})?‌​)+$'
    

    See the regex demo

    Your main building block in this regex is [0-9]+@[0-9]+(\.[0-9]{0,4})? - one or more digits, @, 1+ digits, and then an optional (see the (...)? grouping construct with the ? quantifier that matches 1 or 0 occurrences) sequence of a dot (\.) and 0 to 4 digits ([0-9]{0,4} - if you do not want to allow a dot with no digits afterwards, replace 0 with 1).

    Then, you want to validate the entire string consisting of these blocks with a semi-colon as a separator. You need to use

          ^    +   block   + (      ;    + block  +  )       +         $
          |                  |      |                |       |         |
        string             group   sep             group 1 or more   string 
        start              start                    end  occurrences  end