Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding regex if then statements

Tags:

java

regex

So I'm not sure if I understand how this works and would like a simple explanation to how they work is all. I probably have it way off. A pure regex solution is required, and I don't know if this is possible. If it is, a solution would be awesome too, but a shove in the right direction would be good for my learning process ^_^

This is how I thought the if/then/else option built into my regex engines was formatted:

?(condition)if regex|else regex

I want it to capture a string from a very specific location only when this string exists within a certain section of javascript. Because this is how I thought it worked after a decent amount of research I tried out a few variations of this code but they all ended up something like this.

((?^view_large$)Tables-137(.*?)search.htm)

Also of relevance: I'm using an java based app that has regex searches which pull the data I need so I cannot write an if statement in java which would be my preferred method. It's a pain to have to do it this way, but at the moment I have no other choice. I'm trying really hard for them to allow java code functionality instead of pure regex for more versatile options.

So to summarize, is there even a if/then option in regex and if so how is it formatted for what I'm trying to accomplish?

EDIT: The string that I want to be the "if condition" is like this: if view_large string exists and is not null then capture the exact string 500/ which is captured within the catch all group I used: (.*?)

like image 329
Travis Crum Avatar asked Dec 16 '22 18:12

Travis Crum


2 Answers

There is no conditionals in Java regexp, but you can simulate them by writing two expressions that include mutually exclusive look-behind constructs, like this:

((?<=if )then)|((?<!if )end)

This expression will match "then" when it is preceded by an "if "; it will match "end" when it is not preceded by an "if "

like image 178
Sergey Kalinichenko Avatar answered Dec 31 '22 20:12

Sergey Kalinichenko


The Javadoc for java.util.regex.Pattern mentions, in its list of "Perl constructs not supported by this class":

  • The conditional constructs (?(condition)X) and (?(condition)X|Y).

So, no dice. But you should look through the Javadoc to see if you can achieve what you need by using regex features that it does support. (Or, if you post some more detailed examples, we can try to help.)

like image 34
ruakh Avatar answered Dec 31 '22 21:12

ruakh