简体   繁体   English

需要有关Java正则表达式的帮助

[英]Need help with a regular expression in Javascript

The box should allow: 该框应允许:

  • Uppercase and lowercase letters (case insensitive) 大写和小写字母(不区分大小写)
  • The digits 0 through 9 数字0到9
  • The characters, ! 那些角色, ! # $ % & ' * + - / = ? #$%&'* +-/ =? ^ _ ` { | ^ _`{| } ~ }〜
  • The character "." 人物 ”。” provided that it is not the first or last character 只要它不是第一个或最后一个字符

Try 尝试

^(?!\.)(?!.*\.$)[\w.!#$%&'*+\/=?^`{|}~-]*$

Explanation: 说明:

^         # Anchor the match at the start of the string
(?!\.)    # Assert that the first characters isn't a dot
(?!.*\.$) # Assert that the last characters isn't a dot
[\w.!#$%&'*+\/=?^`{|}~-]*   # Match any number of allowed characters
$         # Anchor the match at the end of the string

Try something like this: 尝试这样的事情:

// the '.' is not included in this:
var temp = "\\w,!#$%&'*+/=?^`{|}~-";

var regex = new RegExp("^["+ temp + "]([." + temp + "]*[" + temp + "])?$");
//                                      ^
//                                      |
//                                      +---- the '.' included here

Looking at your comments it's clear you don't know exactly what a character class does. 查看您的注释,很显然您不完全了解字符类的功能。 You don't need to separate the characters with comma's. 您不需要用逗号分隔字符。 The character class: 人物类:

[0-9,a-z]

matches a single (ascii) -digit or lower case letter OR a comma. 匹配单个(ASCII)数字或小写字母或逗号。 Note that \\w is a "short hand class" that equals [a-zA-Z0-9_] 请注意, \\w是等于[a-zA-Z0-9_]的“简写类”

More information on character classes can be found here: 有关字符类的更多信息,请参见:

http://www.regular-expressions.info/charclass.html http://www.regular-expressions.info/charclass.html

您可以执行以下操作:

^[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~][a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~.]*[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~]$

Here's how I would do it: 这是我的处理方式:

/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*$/

The first part is required to match at least one non-dot character, but everything else is optional, allowing it to match a string with only one (non-dot) character. 第一部分需要匹配至少一个非点字符,但其他所有部分都是可选的,从而允许它仅与一个(非点)字符匹配字符串。 Whenever a dot is encountered, at least one non-dot character must follow, so it won't match a string that begins or ends with a dot. 每当遇到点时,都必须至少跟随一个非点字符,因此它将与以点开头或结尾的字符串不匹配。

It also won't match a string with two or more consecutive dots in it. 它也不会匹配包含两个或多个连续点的字符串。 You didn't specify that, but it's usually one of the requirements when people ask for patterns like this. 您没有指定,但通常是人们要求这种模式时的要求之一。 If you want to permit consecutive dots, just change the \\. 如果要允许连续的点,只需更改\\. to \\.+ . \\.+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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