The following patterns should be matched:
- AAA123
- ABCDEFGH123
- XXXX123
Can I use ".*123"
to achieve this?
The following patterns should be matched:
Can I use ".*123"
to achieve this?
Hey Arpanaa,
Yes, you can use ".*123"
. In regular expressions:
.
matches any character except a newline..*
matches any character (except newline) zero or more times.123
matches the literal characters “123”.So, .*123
will match any string that ends with “123”, preceded by any number of characters.
Hey Arpanaa,
Yes, that will work. However, note that the .
in a regular expression does not match newline characters by default. If you want it to match newline characters, use the Pattern.DOTALL
flag when compiling the pattern. Here’s how you can do it:
Pattern pattern = Pattern.compile(“.*123”, Pattern.DOTALL); Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.matches();
This will create a pattern that matches any character (including newlines) zero or more times, followed by “123”.
Hope this works for you.
Hey @richaaroy
Just to add up to the your answer,
For the specific problem of matching strings ending with “123” and possibly containing uppercase letters before it:
To match “123”, “AAA123”, and “ASDFRRF123”, you can use [A-Z]*123$
. If you need at least one character before “123”, use [A-Z]+123$
.
For a more general solution to matching “any character” in a regular expression:
[\w|\W]{min_char_to_match,}
.[\S]{min_char_to_match,}
.