简体   繁体   中英

Regex for a repeating pattern in C#

I am trying to create a regex to validate a string. The string could be of the following formats (to give an idea of what I am trying to do here):

145/1/3 or

748/57676/6765/454/345 or

45/234 45/235 45/236

So basically the string can contain numbers, spaces and forward slashes and the string can end with a number only. I am new at regex and have gone through many of the questions on the website. But please you have to admit that this is really confusing and difficult to master. And if someone could refer an author or any weblink that can teach regex, that would be really helpful. Thanks in advance mates!

Try this:

^\d(\d|\s|\/)*\d$

\\d = digit character (you can also use [0-9] ). \\s = space character The brackets followed by a star means to repeat a \\d , \\s , or / an infinite amount of times. The final \\d$ means the ending must match a digit.

This should work: ^[/\\d\\s]*\\d$ .

It is looking for the beginning of the string ^ , then 0 or more digits, spaces [/\\d\\s]* followed by a digit \\d then the end of the string $ .

I came up with this

^[0-9]( |[0-9]|\/)*[0-9]$

And used this to test it.

You can see it matches anything that begins (^) with a number, has zero or more (*) of either a space, a number or (|) a forward-slash (/) and ends ($) with a number.

Now that I am aware that the space and / cannot go together and multiple spaces and/or slashes are also not allowed, this RegEx is a better fit for you.

^[0-9]+([ \/][0-9]+)*$

You should use following regular expression:

(\d+(/\d+)*\s*)+

This mean: some digits ( \\d+ ) followed by optional repeating pattern of some digits and \\ ( (/\\d+)* ) followed by an optional number of whitespaces ( \\s* ), all repeated at least once.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM