[Solved] Regex for given pattern


I assume that you use your regex to find matches in the whole
text string (all 3 lines together).

I see also that both your alternatives contain starting ^ and ending $,
so you want to limit the match to a single line
and probably use m regex option.

Note that [^...]+ expression matches a sequence of characters other than
placed between brackets, but it does not exclude \n chars,
what is probably not what you want.

So, maybe you should add \n in each [^...]+ expression.

The regex extended such a way is:

^([^<> \n]+ )+[^<> \n]+$|^[^<> \n]+$

and it matches line 1 and 2.

But note that the first alternative alone (^([^<> \n]+ )+[^<> \n]+$)
also does the job.

It you realy want that line 2 should not match, please specify why.

Edit

To allow any number of spaces at the begin / end of each line,
add * after initial ^ and before final $, so that the
regex (first alternative only) becomes:

^ *([^<> \n]+ )+[^<> \n]+ *$

But it still matches line 2.

Or maybe dots in your test string are actually spaces, but you wrote
the string using dots, to show the numer of spaces?
You should have mentioned it in your question.

Edit 2

Yet another possibility, allowing dots in place of spaces:

^[ .]*((?:[^<> .\n]+[ .])+[^<> .\n]+|[^<> .\n]+)[ .]*$

Details:

  • ^[ .]* – Start of a line + a sequence of spaces or dots, may be empty.
  • ( – Start of the capturing group – container for both alternatives of
    stripped content.

    • (?:[^<> .\n]+[ .])+ – Alternative 1: A sequence of “allowed” chars (“word”) +
      a single space or dot (before the next “word”, repeated a few times.
      This group does not need to be a capturing one, so I put ?:.
    • [^<> .\n]+ – A sequence of “allowed” chars – the last “word”.
  • | – Or.
    • [^<> .\n]+ – Alternative 2: A single “word”.
  • ) – End of the capturing group.
  • [ .]*$ – The final (possibly empty) sequence of spaces / dots + the
    end of line.

Of course, with m option.

2

solved Regex for given pattern