问题
I currently have this validation expression that I am using to validate a complete string: (Thanks to many people including @CinCout)
^((?P *\begin{(?matrix|matrix*|pmatrix|pmatrix*|bmatrix|bmatrix*|Bmatrix|Bmatrix*|vmatrix|vmatrix*|Vmatrix|Vmatrix*|\left|\right)}(?:{c+})?\s(?:(?: *one|two|three){0,3} (-?\d *)?(?:& ?|(\\ *\n)))+ *\end{\g} \s?)|\s\$\s*(?P>matrix) *\$| *\$\$\s(?P>matrix) \$\$|\s\[\s*(?P>matrix) \]|\s\(\s*(?P>matrix) *\))$
I currently force the user to enter "\" after each row of numbers. I realized that this wouldn't work for me since the last row of numbers typically doesn't have "\".
Someone told me a while ago that with regex has difficulty keeping count. That means it would be impossible for regex to know what is the last row. So my only alternative is to make those "\" optional.
I've tried almost everything through trial and error (since I am still a beginner) to make those "\" optional without disrupting the rest of my validation. (I don't want to allow line breaks in any other places then where I currently allow them.) Can someone please take a look at my regex validation and help me out? I think that I need to rearrange some brackets but I gave up trying every single combination...
Here are a couple of examples of text I want passed:
$$
\begin{matrix}{ccc}
10000 & 4 & 3
1 & -2 & 4
1 & 2 & 5
\end{matrix}
$$
$$
\begin{pmatrix}
1 & & 3 \\
1 && two 4 \\
one1 & 2 & -5
\end{pmatrix}
$$
$$
\begin{pmatrix}
1 & 2 & 3 \\
1 & 2 & 4 \\
1 & 2 & -5
\end{pmatrix}
$$
$$
\begin{pmatrix}
1 & 2 & 3
1 & 2 & 4
1 & 2 & -5
\end{pmatrix}
$$
Here is what I don't want passed:
$$
\begin{pmatrix}
1 &
2 & 3 \\
1 &
2 & 4 \\
1 & 2 &
-5 \\
\end{pmatrix}
$$
$$
\begin{pmatrix}
1 & 2 & 3 \\
1 & 2 & 4 \\
1 & 2 & -5 \\
\end{pmatrix}
$$
Basically I don't want to allow any skipped lines before rows finish or double skipped lines anywhere, while keeping everything else intact.
Each row that contains numbers should end in 1 of these ways:
1) the row ends with a number
2) the row ends with "\"
3) the row ends with "&&" or "& &"
I always try to give the user as many spaces as they want in between elements and even after row finishes.
I would greatly appreciate this!
回答1:
Here is your updated regex.
^((?P<matrix> *\\begin{(?<token>matrix|matrix\*|pmatrix|pmatrix\*|bmatrix|bmatrix\*|Bmatrix|Bmatrix\*|vmatrix|vmatrix\*|Vmatrix|Vmatrix\*|\\left|\\right)}(?:{c+})?\s(?:(?: *one|two|three){0,3} *(-?\d* *)?(?:& ?|((?:\\\\)? *\n)))+ *\\end{\g<token>} *\s?)|\s*\$\s*(?P>matrix) *\$| *\$\$\s(?P>matrix) *\$\$|\s*\\\[\s*(?P>matrix) *\\\]|\s*\\\(\s*(?P>matrix) *\\\))$
All you wanted was to make the trailing double slash \\ optional. So I put them in a non-capturing group (?:) and made their presence optional using a ? quantifier.
来源:https://stackoverflow.com/questions/45852655/how-to-make-my-symbol-at-the-end-of-each-row-optional-without-disrupting-my-curr