2010-11-30 2 views
0

Я новичок в регулярных выражений и JavaScript, и мне было интересно, если кто-нибудь знал, что RegEx будет для обнаружения, содержит ли или нет поле ввода следующий тип формата:Для разделенных запятыми

  • В (например, «Test Tag»)

  • Каждый тег, разделенный одной запятой (например, «Автомобили, автомобиль, большая собака, кровать», но не «Автомобили», , Автомобиль, тигр)

Пример того, что я имею в виду это, это было бы действительные теги:

boy, man,girl, woman,tyrannosaurus rex, lion 

И это было бы недействительные теги:

hat, cat, rat, c3po, @gmail 

Поскольку есть недопустимые символы в «@ Gmail».

Он также должен иметь возможность принимать только один тег, если символы являются буквенно-цифровыми.

+0

Вы проверяете ввод или пытаетесь извлечь имена тегов из строки?если вы просто проверяете ввод, это будет гораздо более простое регулярное выражение. – 2010-11-30 17:48:04

+0

Просто подтверждая ввод на данный момент, извлекая часть будет выполнена позже. – ThunderLegs 2010-11-30 17:51:45

+1

Недействительны ли `_`? – 2010-11-30 17:55:38

ответ

2

Предполагая, что вы хотите, чтобы _ и не допускать пробелов в начале или в конце концов, это будет кратчайшее решение:

/^\w(\s*,?\s*\w)*$/ 

Вводя пропуски на концах:

/^\s*\w(\s*,?\s*\w)*\s*$/ 

Удаление _ из допустимые символы:

/^\s*[a-z0-9](\s*,?\s*[a-z0-9])*\s*$/ 

Это регулярное выражение грубой силы, которое я изначально разместил. Это переводит ваши требования к синтаксису регулярных выражений. Я хотел бы оставить его здесь для справки.

/^\s*([a-z0-9]+(\s[a-z0-9]+)*)(\s*,\s*([a-z0-9]+(\s[a-z0-9]+)*))*\s*$/ 
2

Попробуйте что-то вроде этого:

var re = /^(\w+,? ?)+$/; 
var str1 = "boy, man,girl, woman,tyrannosaurus rex, lion"; 
var str2 = "hat, cat, rat, c3po, @gmail"; 
alert(str1.test(re)); // true 
alert(str2.test(re)); // false 

разбив его ... \ ш соответствует символам слова, \ ш + соответствует 1 или более символов слова. ,? ? соответствует дополнительной запятой и пробелу. (Две запятые будут отвергнуты.)() + Вокруг всего говорит один или несколько раз. Наконец,^и $ привязывает его к началу и концу строки, чтобы убедиться, что все согласовано.

1

Если предположить, что нижнее подчеркивание (_) не являются недействительными:

/^(\w+\s?[\w\s]*)(,\s*\w+\s?[\w\s]*)*$/ 

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^» 
Match the regular expression below and capture its match into backreference number 1 «(\w+\s?[\w\s]*)» 
    Match a single character that is a “word character” (letters, digits, and underscores) «\w+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?» 
     Between zero and one times, as many times as possible, giving back as needed (greedy) «?» 
    Match a single character present in the list below «[\w\s]*» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
     A word character (letters, digits, and underscores) «\w» 
     A whitespace character (spaces, tabs, and line breaks) «\s» 
Match the regular expression below and capture its match into backreference number 2 «(,\s*\w+\s?[\w\s]*)*» 
    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
    Note: You repeated the capturing group itself. 
    The group will capture only the last iteration. 
    Put a capturing group around the repeated group to capture all iterations. «*» 
    Match the character “,” literally «,» 
    Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
    Match a single character that is a “word character” (letters, digits, and underscores) «\w+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s?» 
     Between zero and one times, as many times as possible, giving back as needed (greedy) «?» 
    Match a single character present in the list below «[\w\s]*» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
     A word character (letters, digits, and underscores) «\w» 
     A whitespace character (spaces, tabs, and line breaks) «\s» 
Assert position at the end of a line (at the end of the string or before a line break character) «$» 


Created with RegexBuddy 
1

Отдельный вопрос в настоящее время здесь ответа. Как сделать то же самое, но разрешить теги, содержащие не более двух слов?

/^\s*[a-z0-9]+(\s+[a-z0-9]+)?(\s*,\s*[a-z0-9]+(\s+[a-z0-9]+)?)*\s*$/ 

испытано.

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