News for hackers. Stuff that matters.
Re:Is there a regular expression to detect a valid regular e... by tobinfricke on Sunday September 08, 2019 @09:39AM (#20910502)
> Is there a regular expression to detect a valid regular expression?

No, there is not. For example, parentheses in a regex must be balanced, and (famously) there is no regex to detect balanced parentheses.

Re:Is there a regular expression to detect a valid regular e... by mannykannot on Sunday September 08, 2019 @10:42AM (#20910854)
More precisely, it is arbitrarily deep nested clauses that cannot be parsed, on account of true REs not being able to either use recursion or keep count of how deep they are.

https://blogs.msdn.microsoft.com/jaredpar/2008/10/15/regular...

Re:Is there a regular expression to detect a valid regular e... by benj111 on Sunday September 08, 2019 @11:00AM (#20910927)
Can regex engines actually process arbitrarily deep nestings themselves though?

It seems to me it would start getting computationally expensive very quickly to search for those kinds of regexes, so is 'arbitrarily deep' a practical concern for todays hardware?

Re:Is there a regular expression to detect a valid regular e... by gpm on Sunday September 08, 2019 @12:03PM (#20911328)
Yes, regex engines that are designed to do so run in linear time on the size of the regex (as well as linear time with respect to the length of the input).

One such engine is rust's https://github.com/rust-lang/regex

Re:Is there a regular expression to detect a valid regular e... by rstuart4133 on Sunday September 08, 2019 @10:25PM (#20914729)
> One such engine is rust's https://github.com/rust-lang/regex

It can process arbitrary deep nestings? I'm not familiar with it, but I had a look and I can't see anything in there that would allow it to do it. Can you point to syntax that allows it?

In general regex's that run in linear time are based on DFA's (as opposed to NFA's - which is what most use).

A DFA is part of the Chomsky hierarchy of languages that has DFA's at the bottom (aka regex's, least powerful - can't handle recursive structures), a DFA coupled with an infinite stack for memory (aka LR parsers, can't handle context sensitive grammars, also runs in very close to linear time), and finally a DFA coupled with an infinite tape (aka Turing Machine, can do any sort of computation).

In each of these cases the DFA (regex) is essentially a computer program and all they are doing is allowing it to store stuff on various kinds of memory (none, stack, tape with arbitrary movements). An interesting corollary of this is any computer program can be expressed as a DFA.

Re:Is there a regular expression to detect a valid regular e... by burntsushi on Thursday September 12, 2019 @07:03AM (#20950093)
> It can process arbitrary deep nestings?

The GP is presumably citing it as an example of a linear time regex, and not as something that can parse arbitrarily deep nestings. Note that "linear time regex engines" is a characterization that holds the size of the regex constant, such that "linear time" is with respect to the input only. The actual worst case time complexity of such regex engines is O(m * n), where m ~ len(regex) and n ~ len(input). So even with a linear time regex engine, if you bloat the size of the regex, you'll make searching slower. But, it will still be done linearly with respect to the size of the input.

> In general regex's that run in linear time are based on DFA's (as opposed to NFA's - which is what most use).

No. Please stop spreading the misuse of these terms. DFAs and NFAs have very precise meanings. It's one thing to call things regexes that aren't actually regular, but DFAs and NFAs should retain their precise theoretical meaning. A linear time regex engine such as Rust's `regex` crate uses both DFAs and NFAs in its implementation.

The Perl and PCRE folks (along with Jeffrey Friedl) have bastardized this terminology. PCRE for example claims to provide a "DFA" regex engine in its API, but it's actually an NFA. The main implementation inside PCRE (and Perl) is backtracking oriented, and carries with it much more power than an NFA. If it didn't, then the NFA could be executed in linear time, because NFAs and DFAs have equivalent power.

> An interesting corollary of this is any computer program can be expressed as a DFA.

No they can't. You're confusing terminology quite a bit here.

Re:Is there a regular expression to detect a valid regular e... by ridiculous_fish on Sunday September 08, 2019 @05:44PM (#20913637)
Does "linear wrt A and linear wrt B" mean O(A*B) or O(A+B)?
Re:Is there a regular expression to detect a valid regular e... by gpm on Sunday September 08, 2019 @05:53PM (#20913682)
It means O(AB), but is carefully worded to not say (or suggest) it's not possible to do O(A+B) which is a subset of O(AB) ;)

I'm not sure if it's possible to match regex with that time complexity, it looks like the implementation I referenced is O(AB). https://docs.rs/regex/1.3.1/regex/#untrusted-input.

(star symbol removed because hn decided to turn them into a block of italics)

Re:Is there a regular expression to detect a valid regular e... by mannykannot on Sunday September 08, 2019 @11:11AM (#20910997)
There is an importance to theoretical considerations that goes beyond their immediate practical applications. Ultimately, it comes down to how well one understands what is going on.

Having said that, I think there are practical applications. Suppose you were unaware of this result, and thought a true RE could validate your input? A more knowledgeable attacker might be able to craft an input that exploits the inherent limitations of your validator.

Also in practice, attempting to write a true RE to parse a language that allows restricted recursion rapidly becomes complicated. It is the wrong tool for the job.

Re:Is there a regular expression to detect a valid regular e... by jessaustin on Sunday September 08, 2019 @11:33AM (#20911119)
Just considering the language of balanced parentheses, the only memory needed is a single integer to track depth. If we see a "(", increment. If we see a ")", decrement. If we never go negative and end up with zero, that's a balanced parentheses expression. (To be clear, the parser I've described is not a regex parser.)

Adding the rest of the regex machinery makes this a bit more complex, but in general, if the computer can store the string, it can check whether it's regular.

Re:Is there a regular expression to detect a valid regular e... by taejo on Monday September 09, 2019 @04:08AM (#20916124)
As you say, this is not a regex parser, but some readers may not know the theorem that the regular languages are exactly those which can be parsed by a Turing machine with constant memory, and parenthesis count can have log n bits.

In fact, any Turing machine using o(log log n) space recognizes a regular language (so there is an equivalent machine using O(1) space).

Re:Is there a regular expression to detect a valid regular e... by dyarosla on Sunday September 08, 2019 @12:14PM (#20911401)
This only works if you have a single type of parenthesis. Is that applicable to regex expressions in general that only ()’s can nest?
Re:Is there a regular expression to detect a valid regular e... by gpm on Sunday September 08, 2019 @12:54PM (#20911660)
As typically defined academically, yes. In the real world things might be more complex, but I think it would hold true for many implementations.

Academically a regex is a string of of:

- character literals

- "epsilon" characters (meaning empty string)

- "+" characters (which means either what we see before the + or what we see after the +, in real-world regex these are usually represented as | instead of + as well as used implicitly in constructs like [a-zA-Z])

- "*" characters (same meaning as in real-world regex)

- And parentheses to allow controlling the order of operations

Re:Is there a regular expression to detect a valid regular e... by Piskvorrr on Sunday September 08, 2019 @01:36PM (#20911976)
In other words, "if we build a state machine which is different from a regex, it will perform differently than a regex would." That's trivially true, but is it interesting beyond restating "there is no Silver Bullet"?
Re:Is there a regular expression to detect a valid regular e... by gpm on Sunday September 08, 2019 @01:50PM (#20912069)
Technically we aren't discussing the regex itself here but the syntax for defining a regex.

You could use a different syntax for defining the same regex, and that syntax could have different properties. For instance you could use parantheses like racket where "(...)" and "[...]" have the same meaning, but "(...]" is not well formed syntax (if I remember my racket correctly). Using such a syntax to define regex a counter would no longer suffice to decide if a string is a regex.

Re:Is there a regular expression to detect a valid regular e... by jessaustin on Sunday September 08, 2019 @10:11PM (#20914671)
You could have a stack of (paren-type, integer) pairs. If the paren has a different type than the top pair on the stack (or the stack is empty), push a new pair with the integer set to one. If the integer goes to zero, pop the pair. At the end of the expression, you have to have an empty stack.
Re:Is there a regular expression to detect a valid regular e... by nightfly on Sunday September 08, 2019 @02:01PM (#20912158)
)))((()(()
Re:Is there a regular expression to detect a valid regular e... by gerdesj on Sunday September 08, 2019 @05:59PM (#20913709)
When I check brackets by hand or manually I do actually get my hands out and when I say open I uncurl a finger, and when I say close, I furl a finger. "Open, open, open, close, open, close, close, close". Provided I have no fingers on display at the end, then the brackets are balanced. They might not be in the right place but at least they are balanced. If I find myself starting with close then I close the lid and go and do something else.

I'm sure some sort of rather cheap algorithm falls out of the above. It wont guarantee correctness in what the balanced brackets actually contain but they will at least be balanced.

Re:Is there a regular expression to detect a valid regular e... by sixstringtheory on Sunday September 08, 2019 @02:07PM (#20912210)
Good edge case. I’d say to immediately return an ‘unbalanced’ result once the count goes negative.
Re:Is there a regular expression to detect a valid regular e... by lioeters on Sunday September 08, 2019 @02:54PM (#20912570)
((((()
Re:Is there a regular expression to detect a valid regular e... by detaro on Sunday September 08, 2019 @02:56PM (#20912589)
doesn't end up with zero at the end, rejected?
Re:Is there a regular expression to detect a valid regular e... by lioeters on Sunday September 08, 2019 @06:29PM (#20913817)
I was just trying to suggest a possible edge case, a failing test.
Re:Is there a regular expression to detect a valid regular e... by jessaustin on Sunday September 08, 2019 @10:05PM (#20914653)
"never go negative"
Re:Is there a regular expression to detect a valid regular e... by jameshart on Sunday September 08, 2019 @11:04AM (#20910959)
This is true if you want to handle arbitrarily deep nested parents.

But any given string you are asked to validate to see if it is a regex will be a finite length, and contain a finite number of opening paren characters. So it’s maximum possible nesting depth is known.

And you can construct, fairly trivially, a regex that can validate paren nesting up to a fixed depth.

So, in practice, you could use a regular expression to validate the paren nesting of any given string - if you were allowed to prepare the regex based on the string length, or on running another regex over the string first.

What I suspect you might not be able to validate is that in a regex, while [a-z] is valid, [z-a] is not.

Re:Is there a regular expression to detect a valid regular e... by daveFNbuck on Sunday September 08, 2019 @11:42AM (#20911180)
If you allow generating a regular expression based on string length, you can validate any computable language with a regular expression. It's trivial to just run a solver on all strings of that length and or the accepted ones together.

> What I suspect you might not be able to validate is that in a regex, while [a-z] is valid, [z-a] is not.

It's fairly trivial to validate things like a-z being valid in a character class while z-a isn't. There are only finitely many legal ranges. You can just list them all, like \[(a-a|a-b|a-c|...|z-z)\].

Re:Is there a regular expression to detect a valid regular e... by repsilat on Sunday September 08, 2019 @11:45AM (#20911209)
For a fixed input length all languages are decidable by regular expressions. Trivially, the union of all valid input strings of that length, like "(abc|def|...)".

It's not an interesting property.

Re:Is there a regular expression to detect a valid regular e... by jimhefferon on Sunday September 08, 2019 @01:09PM (#20911767)
The problem is that "regular expression" is equivocal.

Sometimes you hear "regular expression" used to mean the language of things accepted by some Finite State machine. Lots of folks on HN took a Theory of Computation class and learned about these in that class. In that meaning, yes, you are right.

But sometimes in professional conversations you hear "regular expression" used to mean the strings that can be matched using, say, Perl's regular expressions. I know I have heard it used that way often. Since Perl regular expressions can accept anything a Turing machine can accept, the answer to the question in this case is yes.

Re:Is there a regular expression to detect a valid regular e... by wahern on Sunday September 08, 2019 @07:08PM (#20913958)
Very few people know that Perl's regex engine (since 5.10) supports recursion. And recursive matching cannot perform recursive captures, which is why at best it can only be used to validate a string, not parse it, making it not particularly useful in practice. For these reasons I would never assume that someone using the term "regular expression" inclusively of Perl would have in mind such capabilities. IME, such a loose definition simply implies things like zero-width assertions, backcaptures, etc.

Here's a proof-of-concept Perl 5.10+ JSON validator I came up with for a presentation to Perl engineers introducing PEGs and Lua's LPeg module. Of the 20-30 people in the room, I doubt anybody in the audience knew this was even possible with Perl.

  my $grammar = qr{
  ^(?&Value) $
  (?(DEFINE)
    (?<Value> \s∗ (?:
        (?&Array)
      | (?&Object)
      | (?&Boolean)
      | (?&Number)
      | (?&String)
      | (?&Null)
    ) \s∗ )
    (?<Array> \[ \s∗ (?:(?&Value) (?:\s∗,\s∗ (?&Value))∗)? \s∗ \])
    (?<Object> \{ \s∗ (?:(?&KeyV) (?:\s∗,\s∗ (?&KeyV))∗)? \s∗ \})
    (?<KeyV> \s∗ (?:(?&String) \s∗:\s∗ (?&Value))) \s∗
    (?<Boolean> true | false)
    (?<Number> \d+)
    (?<String> "[^\"]∗")
    (?<Null> null)
  )
  }xs;
Note: I was trying to fit it all on a single slide, so the definition for String doesn't handle escaped characters. There may be other deficiencies. I copy+pasted this from the PDF slide deck as I can't find the original Beamer source. Any broken spacing and Unicode substitutions probably aren't original.
Re:Is there a regular expression to detect a valid regular e... by mannykannot on Sunday September 08, 2019 @02:36PM (#20912425)
Sort of, but if (and only if) you know what a regular expression formally means, you can disambiguate the equivocation introduced by ambiguous usage.
Re:Is there a regular expression to detect a valid regular e... by tgv on Sunday September 08, 2019 @11:19AM (#20911045)
It depends on the representation. If the representation is in the FSA format (state, character, state), it becomes nearly trivial.
Re:Is there a regular expression to detect a valid regular e... by ggrrhh_ta on Sunday September 08, 2019 @11:55AM (#20911276)
Very underrated comment. Very good point to give food for thought although I think it is clear that it was meant to be on the usual textual representation using the simplest re language (without extensions).
Re:Is there a regular expression to detect a valid regular e... by morelisp on Sunday September 08, 2019 @12:08PM (#20911359)
An analogous problem for this representation would be detecting transitions to undefined states, or ambiguous (duplicate) transitions.
Re:Is there a regular expression to detect a valid regular e... by tgv on Monday September 09, 2019 @03:17AM (#20915907)
I didn't verify it, but my intuition says that can't be done with a CFG; it seems at least context-sensitive.
Re:Is there a regular expression to detect a valid regular e... by lioeters on Sunday September 08, 2019 @02:52PM (#20912555)
> (famously) there is no regex to detect balanced parentheses

God, I remember running into this wall with an in-company domain-specific language that used regex as its tokenizer/parser.

Adding support for nested structures required us to untangle the whole thing and rewrite the regex into explicit algorithms. Fortunately the regex was only a few pages long..

In short, I agree with you that regex cannot parse regular expressions completely. Would be happy to be proven wrong, though!

Re:Is there a regular expression to detect a valid regular e... by blibble on Sunday September 08, 2019 @05:06PM (#20913419)
> In short, I agree with you that regex cannot parse regular expressions completely. Would be happy to be proven wrong, though!

the proof that you can't parse nested pararetheses with a regular language is a pretty standard part of first year computer science

Re:Is there a regular expression to detect a valid regular e... by lioeters on Sunday September 08, 2019 @06:29PM (#20913818)
It doesn't stop some of us from trying though! :)
Re:Is there a regular expression to detect a valid regular e... by tobinfricke on Sunday September 08, 2019 @10:27AM (#20910733)
Follow-up question: without the grouping parentheses, is the regex language regular?
Re:Is there a regular expression to detect a valid regular e... by trisiak on Sunday September 08, 2019 @11:13AM (#20911009)
Yes, but you're taking too much. Without grouping, regex is weaker than regular languages.

Grouping & capturing parentheses can stay. It's only the back-referrences that you need to remove.

Re:Is there a regular expression to detect a valid regular e... by gbacon on Sunday September 08, 2019 @03:36PM (#20912856)
Regex matching with backreferences is NP-hard.

https://perl.plover.com/NPC/

Re:Is there a regular expression to detect a valid regular e... by saltcured on Sunday September 08, 2019 @04:47PM (#20913315)
Grouping is very useful, but I think you can get pretty far in practical patterns with a limit of k-nesting for k=0..3 or so. That pattern language would still be regular.
Re:Is there a regular expression to detect a valid regular e... by lonelappde on Sunday September 08, 2019 @10:32AM (#20910779)
Yes but it's mostly useless, since it can't match (variable-count) repeated strings of length greater than 1. Goruping isn't only about extraction.
Re:Is there a regular expression to detect a valid regular e... by raldi on Sunday September 08, 2019 @10:11AM (#20910639)
Sure there is. Read the linked answer, or just google it.

Example:

https://regular-expressions.mobi/recurse.html?wlr=1

Re:Is there a regular expression to detect a valid regular e... by jtanderson on Sunday September 08, 2019 @10:21AM (#20910703)
Right but parent is thinking of the quesion "is the language of valid regular expressions itself regular?", which a very different question and of course false by an easy application of the pumping lemma. However, as shown in the SO answer, they "cheat" by using some features that don't align completely with the mathematical definitions.

edit: typo.

Re:Is there a regular expression to detect a valid regular e... by josalhor on Sunday September 08, 2019 @10:15AM (#20910661)
It depends if we're talking regex in the mathematical sense or in the programming one.