I need a pattern to match words like APPLE:
or PEA开发者_StackOverflowR:
[A-Z][:]
will match the R:
but not the whole word and thus gives me a false when I try to match.
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:
[A-Z]+:
Just add a "quantifier":
/[A-Z]+:/
Note you don't need a character class for a single character.
How about \b[A-Z]+:
? The \b
is for checking a word boundary btw.
\b
can be used to capture characters only in a word-boundary ie between the start and end of a word.
[A-Z]
indicates a range of characters and specifying A-Z specifically matches the range of characters from capital A to capital Z. In other words, only upper case letters.
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.
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]+\:
精彩评论