[英]Regex - Match Specific Character Anywhere
I'm trying to match against a string that is a mix of letters and special characters. 我正在尝试匹配由字母和特殊字符组成的字符串。
ex: 例如:
THIS!IS*A STRING
I've tried to put together a (probably noobish) regex that does this for the characters I want (Java): 我尝试将一个(可能是笨拙的)正则表达式放在一起,以针对我想要的字符(Java)执行此操作:
"\\w{1,40}&*-*\\.*`*\\(*\\)*\\/*\\\\*!*,*\\** *"
It seems to work but only when the special character is at the end of the line. 它似乎有效,但仅当特殊字符在行尾时才有效。 Is there a way to match it regardless of position?
有没有一种方法可以匹配它而不管位置如何?
EDIT1: EDIT1:
Spec: 规格:
Characters allowed are: AZ az 0-9 – . ' ) ( & / \\ ! , * space
允许的字符为:
AZ az 0-9 – . ' ) ( & / \\ ! , * space
AZ az 0-9 – . ' ) ( & / \\ ! , * space
. AZ az 0-9 – . ' ) ( & / \\ ! , * space
。
EDIT2: EDIT2:
Getting closer I think: 我认为越来越近:
"[\\w-.`()&/\\!,* ]+"
Seems to be giving me what I want but when I add a range I get an exception: 似乎是在给我我想要的东西,但是当我添加范围时出现异常:
"[\\w{1,40}-.`()&/\\!,* ]+"
thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 10
[\w{1,40}-.`()&/\!,* ]+
^
So I think I have achieved it by... 所以我认为我已经通过...实现了
The hyphen is a range char and needs to be at the start or end of the character class. 连字符是范围char,必须位于字符类的开头或结尾。
I shifted the range outside the character class and this looks to have fixed the issue of it being ignored if it's inside a character class. 我将范围移到了字符类之外,这似乎已经解决了如果它在字符类内部则被忽略的问题。
"[\\w.`()&/\\!,* -]{1,40}+"
Your code works fine: 您的代码工作正常:
String s = "THIS!IS*A STRING";
Pattern p = Pattern.compile("\\w{1,40}&*-*\\.*`*\\(*\\)*\\/*\\\\*!*,*\\** *");
Matcher m = p.matcher(s);
while (m.find())
System.out.println(m.group());
The results are: 结果是:
THIS!
IS*
A
STRING
If you want to use String.matches, you should extend the pattern to match whole strings. 如果要使用String.matches,则应扩展模式以匹配整个字符串。
String s = "THIS!IS*A STRING";
System.out.println(s.matches("(\\w{1,40}&*-*\\.*`*\\(*\\)*\\/*\\\\*!*,*\\** *)*"));
// -> true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.