2012-05-17 3 views
8

У меня есть строка, которая должна быть на следующем формате:Validate строки на основе формата

ХХХХ-ХХ-XXX-XXXX-XXXXXXXXXX-Х

, где Х представляет собой целое число. Число целых чисел не имеет значения. Мне просто нужно, чтобы убедиться, что строки:

  • начинается и заканчивается с целым числом
  • содержит только целые числа, разделенные тире

, что было бы самым простым способом проверить, что?

+4

Регулярные выражения будут выполнять эту работу. – ken2k

ответ

13

Это регулярное выражение должно сделать трюк. Он использует отрицательный lookbehind, чтобы избежать совпадения нескольких тире в строке.

^\d(\d|(?<!-)-)*\d$|^\d$ 

^  ^ ^^
|  |  | -- is a single digit, or 
|  |  ------- ends with a digit 
|  ----------------consists on digits or dashes not preceded by dashes 
---------------------starts with a digit 

Вот C# код, который иллюстрирует его использование (в том числе на ideone):

var r = new Regex("^\\d(\\d|(?<!-)-)*\\d$|^\\d$"); 
Console.WriteLine(r.IsMatch("1-2-3")); 
Console.WriteLine(r.IsMatch("1-222-3333")); 
Console.WriteLine(r.IsMatch("123")); 
Console.WriteLine(r.IsMatch("1-2-3-")); 
Console.WriteLine(r.IsMatch("1")); 
Console.WriteLine(r.IsMatch("-11-2-3-")); 
+0

у вас есть дополнительный) на ваш ответ. Правильно было бы^\ d (\ d | (? Diego

+0

@Diego Вы правы, образец, который я связал с ideone, не имеет этой дополнительной круглой скобки. Я отредактировал ответ, спасибо! – dasblinkenlight

+0

Я принял ваш ответ, потому что именно тот имел дело с dasehs подряд. Большое спасибо – Diego

4

вы можете написать регулярное выражение, которое делает трюк.

Чем вы можете использовать это регулярное выражение для проверки вашей строки

^ ---->Start of a string. 
$ ---->End of a string. 
. ----> Any character (except \n newline) 
{...}----> Explicit quantifier notation. 
[...] ---->Explicit set of characters to match. 
(...) ---->Logical grouping of part of an expression. 
* ---->0 or more of previous expression. 
+ ---->1 or more of previous expression. 
? ---->0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string. 
\ ---->Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below. 
\w ----> matches any word character, equivalent to [a-zA-Z0-9] 
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9]. 
\s ----> matches any white space character, equivalent to [\f\n\r\v] 
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v] 
\d ----> matches any decimal digits, equivalent to [0-9] 
\D----> matches any non-digit characters, equivalent to [^0-9] 

\a ----> Matches a bell (alarm) \u0007. 
\b ----> Matches a backspace \u0008 if in a [] character class; otherwise, see the note following this table. 
\t ---->Matches a tab \u0009. 
\r ---->Matches a carriage return \u000D. 
\v ---->Matches a vertical tab \u000B. 
\f ---->Matches a form feed \u000C. 
\n ---->Matches a new line \u000A. 
\e ---->Matches an escape \u001B 

$number ----> Substitutes the last substring matched by group number number (decimal). 
${name} ----> Substitutes the last substring matched by a (?) group. 
$$ ----> Substitutes a single "$" literal. 
$& ----> Substitutes a copy of the entire match itself. 
$` ----> Substitutes all the text of the input string before the match. 
$' ----> Substitutes all the text of the input string after the match. 
$+ ----> Substitutes the last group captured. 
$_ ----> Substitutes the entire input string. 

(?(expression)yes|no) ----> Matches yes part if expression matches and no part will be ommited. 
более

информация на

http://geekswithblogs.net/brcraju/archive/2003/10/23/235.aspx

7

Используйте регулярное выражение.

^\d[-0-9]+\d$ 

Предполагается, что длина строки не менее трех символов.

Разбивка:

^ - match start of string 
\d - match a digit 
[ - start of character class containing: 
-  - a dash 
0-9 - 0 to 9 
] - end of character class 
+ - match one or more of the previous 
\d - match a digit 
$ - match end of string 

Вы можете изменить + к * сделать 2 цифры строки в силе, и добавить чередование сделать 1 значные строки действует так же:

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

Примечание: В .NET, \d будет соответствовать any Обозначение Unicode (так, например, арабские цифры будут совпадать) - если вы этого не хотите, замените \d на [0-9] в каждом месте.

+0

+1 очень хорошее спасибо. Только проблема заключается в том, что он не проверяет 1 или 12 – Diego

+0

@Diego - Нет, я сделал предположение, что это предполагает 3 символа. Вы можете использовать чередование для соответствия 1 и 2 цифрам. Ответ обновлен. – Oded

+0

спасибо Одед. Только для вашей информации он все еще проверяет 1--1 (тире в строке). Но это нормально, dasblinkenlight уже опубликовал рабочее решение. Еще раз спасибо за ваше время – Diego

Смежные вопросы