kadir950
kadir950

Reputation: 117

RegEx start with, contains these, not end with?

I need a regular expression to find all comparison parts in the following example.

        var magicalRegex = "";
        var example = '({Color}=="red"|{Color}=="yellow")&{Size}>32';
        example.replace(magicalRegex, function (matchedBlock) {
            console.log(matchedBlock);
        });

        //so i want to see the following result on console 
        //{Color}=="red"
        //{Color}=="yellow"
        //{Size}>32

In fact i did some things but couldn't complete, also you may check the following template which i couldn't complete.

\{.*?(==|>)

enter image description here

https://regex101.com/r/aodDeX/1

Thanks

Upvotes: 1

Views: 2147

Answers (1)

ctwheels
ctwheels

Reputation: 22817

Answer

According to the example you have on regex101 as well as the string you have in your code snippet (two different strings) the following regex will do exactly what you want.

Answer 1

({.*?}(?:==|>)(?:\d+|(?:(["']?).*?\2)))

You can see this regex in use here

Answer 2

Note that I've added both single and double quotes in the above regex. If you only need double quotes, use the following regex.

({.*?}(?:==|>)(?:\d+|".*?"))

You can see this regex in use here

Explanation

These regular expressions work as follows:

  1. Match {, followed by any character (except newline) any number of times, but as few matches as possible, followed by }
  2. Match == or >
  3. Match a digit one to unlimited times or match a quoted string (any character any number of times, but as few matches as possible) e.g. "something"

The regex captures the entire section and if you look at the examples on regex101 as presented, you can see what each capture group is matching. You can remove the capture groups if this is not the intended use.


Expected Results

Input

Note that the two strings below were used for testing purposes. One string is present in the question and the other is present in the link provided by the OP.

({Renk}=="kirmizi"or{Renk}=="sari")or{Size}>32
({Color}=="red"|{Color}=="yellow")&{Size}>32

Output

Note that the output mentioned hereafter specifies what is matched/also capture group 1 (since the whole regex is in a capture group). Any other groups are disregarded as they are not important to the overall question/answer.

{Renk}=="kirmizi"
{Renk}=="sari"
{Size}>32

{Color}=="red"
{Color}=="yellow"
{Size}>32

Upvotes: 2

Related Questions