[英]Regular Expression Pattern to Match Words in All Caps That Are Followed By a colon
I need a pattern to match words like APPLE:
or PEAR:
我需要一个模式来匹配像
APPLE:
或PEAR:
这样的词
[AZ][:]
will match the R:
but not the whole word and thus gives me a false when I try to match. [AZ][:]
将匹配R:
但不是整个单词,因此当我尝试匹配时给我一个错误。
Can anybody help?有人可以帮忙吗?
You want to match one or more capital letter which means you need to use a +
.您想匹配一个或多个大写字母,这意味着您需要使用
+
。 Also your :
doesn't need to be in a character class:您的
:
也不需要在字符 class 中:
[AZ]+:
Just add a "quantifier":只需添加一个“量词”:
/[A-Z]+:/
Note you don't need a character class for a single character.请注意,单个字符不需要字符 class。
How about \b[AZ]+:
? \b[AZ]+:
怎么样? The \b
is for checking a word boundary btw. \b
用于检查单词边界。
\b
can be used to capture characters only in a word-boundary ie between the start and end of a word. \b
只能用于捕获单词边界中的字符,即在单词的开头和结尾之间。
[AZ]
indicates a range of characters and specifying AZ specifically matches the range of characters from capital A to capital Z. In other words, only upper case letters. [AZ]
表示字符范围,指定 AZ 专门匹配从大写 A 到大写 Z 的字符范围。也就是说,只有大写字母。
End the query by trying to match a semicolon and you'll find matches of a capital letter word immediately followed by a single semi-colon.通过尝试匹配分号来结束查询,您会发现匹配的大写字母单词紧跟一个分号。
You can use the regular expression in Java like below.您可以使用 Java 中的正则表达式,如下所示。
import java.util.regex.*;
public class RegexExample {
System.out.println(
Pattern.matches("\b[A-Z]+:", "data: stuff, MIX!: of, APPLE: or, PEAR: or, PineAPPLes: yay!")
);
}
I recommend finding an online playground for regular expressions.我建议为正则表达式找到一个在线游乐场。 Iterating and experimenting with regexes for a project can be a fast way to learn the limitations and find ways to simplify or improve an expression.
为项目迭代和试验正则表达式是了解限制并找到简化或改进表达式的方法的快速方法。
you need to use the +
operator to get a match to all characters in the group您需要使用
+
运算符来匹配组中的所有字符
try with regex:尝试使用正则表达式:
[A-Z]+\:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.