Can anyone please help me with a regex pattern that will match and check the following scenarios? I'm trying to match text that's separated with return characters. Each line should only have 3 digits (\\d{3}) in it and up to 100 lines.
This is ok:
123
456
789
This is not ok:
123
123789
456
This is not ok (note the empty line in the middle and at end):
123
456
I would appreciate any suggestion and help. thanks.
So the entire file must look like this? Then try
new Regex(@"\A(?:\d{3}\r?\n)*\z")
Explanation:
\A # Start of string
(?: # Match the following (non-capturing) group:
\d{3} # - three digits
\r?\n # - one CRLF or LF (linebreak)
)* # any number of times (0 or more)
\z # until the very end of the string
If the file might not end with a newline (not sure from your description), you can use
new Regex(@"\A(?:\d{3}\r?$\n?)*\z", RegexOptions.Multiline)
This initially makes newlines optional ( \\r?\\n?
) but ensures that there is a line ending after every three-character bit by placing the end-of-line anchor $
between CR and LF, which is where (strangely) .NET thinks it should match.
One way to do this is simply to check each line against your initial regex (\\d{3}). Another way is to add \\r \\n to your regex and allow for repeats
"(\d{3}\r?\n)*"
in order to filter out case 3, you just need to add beginning and end to show you want to match the entire file; (^ specifies beginning, $ specifies end)
"^(\d{3}\r?\n)*$"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.