I need a pattern to match words like APPLE:
or PEAR:
[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?
A colon has no special meaning in Regular Expressions, it just matches a literal colon.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.
Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions. As a workaround, use the regular expression standard of ASCII.
For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With