This works:

CopyString rex = "^\\d+\\.\\s\\p{Lu}+.*";

System.out.println("1. PTYU fmmflksfkslfsm".matches(rex));
// true

System.out.println(". PTYU fmmflksfkslfsm".matches(rex));
// false, missing leading digit

System.out.println("1.PTYU fmmflksfkslfsm".matches(rex));
// false, missing space after .

System.out.println("1. xPTYU fmmflksfkslfsm".matches(rex));
// false, lower case letter before the upper case letters

Breaking it down:

  • ^ = Start of string
  • \d+ = One or more digits (the \ is escaped because it's in a string, hence \\)
  • \. = A literal . (or your original [.] is fine) (again, escaped in the string)
  • \s = One whitespace char (no need for the {1} after it) (I'll stop mentioning the escapes now)
  • \p{Lu}+ = One or more upper case letters (using the proper Unicode escape — thank you, tchrist, for pointing this out in your comment below. In English terms, the equivalent would be [A-Z]+)
  • .* = Anything else

See the documentation here for details.

You only need the .* at the end if you're using a method like String#match (above) that will try to match the entire string.

Answer from T.J. Crowder on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_regex.asp
Java Regular Expressions
Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions.
Discussions

Validating a string using regex
The pattern you specified, [a-zA-Z], will only match against individual characters. The Matcher returned by pattern.matcher() tells you if the pattern matches the entire string. Any string with multiple characters won't match this pattern. More on reddit.com
🌐 r/learnjava
6
3
January 1, 2024
How to use Java Regex?
If regex is a must, then I'd define a pattern which looks for key=value pair preceded by the start of the string or a comma and followed by the end of the string or a comma. I'd then specify the maximum allowed occurences for a match to be open ended e.g. match it as often as possible. (I suggest using positive lookbehinds and lookaheads) Using String.split() you'd first split the whole line by comma and then each split segment by the first equal sign. For both solutions you need to make sure that the delimiters , and = don't exist in either the key name or value OR that they are properly escaped (which you need to consider in your chosen method as well). More on reddit.com
🌐 r/learnprogramming
5
4
December 24, 2012
Still no split without regex?

Fact: String.split is error prone and slower.

without interpreting its argument as regex

In JDK, String.split actually splits w/o regex if your separator is a one non-regexp char, but it's an implementation detail...

IMHO, all String methods that take regexp String should be deprecated and replaced with a new version that takes explicit java.util.regex.Pattern param, e.g.: String.replaceAll(String, String) -> String.replaceAll(Pattern, String) (or even better: String.replaceAllSecondParamIsNOTWhatYouThink(Pattern, String) - not a joke - replaceAll is often used incorrectly)

More on reddit.com
🌐 r/java
32
16
January 18, 2015
Regular expression for parsing suffixes and prefixes?
For prefixes, you could try: \bpe[^\s]+ # searching for words that have 'pe' prefix. For suffixes, it would be the reverse: [^\s]+er\b # searching for words that have 'er' suffix. For case sensitivity, you just need to turn on or off the i flag or add (?i) to the beginning of your regex. Demos of prefix and suffix . More on reddit.com
🌐 r/regex
2
3
May 7, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › java › regular-expressions-in-java
Regular Expressions in Java - GeeksforGeeks
December 9, 2025 - In Java, regular expressions are supported through the java.util.regex package, which mainly consists of the following classes: Pattern: Defines the regular expression. Matcher: Used to perform operations such as matching, searching and replacing. PatternSyntaxException: Indicates a syntax error in the regular expression. The Pattern class compiles regex strings into pattern objects.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... A compiled representation of a regular expression. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences ...
🌐
Regular-Expressions.info
regular-expressions.info › java.html
Using Regular Expressions in Java
It is important to remember that String.matches() only returns true if the entire string can be matched. In other words: "regex" is applied as if you had written "^regex$" with start and end of string anchors. This is different from most other regex libraries, where the “quick match test” method returns true if the regex can be matched anywhere in the string.
🌐
Vogella
vogella.com › tutorials › JavaRegularExpressions › article.html
Regular expressions in Java - Tutorial
This tutorial describes the usage ... examples for common use cases, and important security considerations. A regular expression (regex) defines a search pattern for strings....
Find elsewhere
🌐
Coders Campus
coderscampus.com › home › mastering regular expressions
Mastering Regular Expressions - How to Program with Java
April 9, 2021 - Any guesses on what matches you would get from this regex? It may not be obvious at first, but this will actually make three matches, and those words are: bat, cat and hat. You see why? The first three letters are encased in those square brackets, so they form a character class where Java matches either the letter: b, c or h. Then it will append the search for a String literal “at”. So what do you get when you combine the letters b, c or h with the String “at”? You get: bat, cat or hat.
🌐
Medium
medium.com › @AlexanderObregon › beginners-guide-to-java-regular-expressions-regex-8122a5933352
Beginner’s Guide to Java Regular Expressions (Regex)
March 23, 2024 - Groups are created in regex by enclosing part of the regex in parentheses (). This is not only useful for applying quantifiers to part of the regex but also for extracting information from strings. For example, (\d\d) matches a two-digit number and captures it as a group. Let’s modify the previous example to find and extract the first word from the text: import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "The quick brown fox jumps over the lazy dog."; String patternString = "(\\w+)"; // Matches and captures the first word Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.println("The first word is: " + matcher.group(1)); // Outputs "The" } } }
🌐
Okta Developer
developer.okta.com › blog › 2022 › 04 › 19 › java-regex
A Quick Guide to Regular Expressions in Java | Okta Developer
April 19, 2022 - For example, if you use the regular expression ab*, you’re issuing an instruction to match a string that has an a followed by zero or more b’s. So strings like ab, abc, abbc, etc. will match our regular expression. The asterisk symbol, *, denotes the number of times a character or a sequence of characters may occur. Regular expressions make finding patterns in text much easier. Some high-level use cases include: ... Regular expressions are also well-supported in many programming languages. Supporting classes for regular expressions in Java are available in the java.util.regex package.
🌐
JRebel
jrebel.com › blog › java-regular-expressions-cheat-sheet
Java Regular Expressions (Regex) Cheat Sheet | JRebel
A regular character in the Java Regex syntax matches that character in the text. If you'll create a Pattern with Pattern.compile("a") it will only match only the String "a". There is also an escape character, which is the backslash "\".
🌐
Baeldung
baeldung.com › home › java › a guide to java regular expressions api
A Guide To Java Regular Expressions API | Baeldung
January 8, 2024 - However, this class has another variant of the compile method that accepts a set of flags alongside the regex argument, which affects the way we match the pattern. These flags are simply abstracted integer values. Let’s overload the runTest method in the test class, so that it can take a flag as the third argument: public static int runTest(String regex, String text, int flags) { pattern = Pattern.compile(regex, flags); matcher = pattern.matcher(text); int matches = 0; while (matcher.find()){ matches++; } return matches; }
🌐
Regex101
regex101.com
regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.
🌐
CodeGym
codegym.cc › java blog › strings in java › regular expressions in java
Java RegEx Regular expressions | CodeGym
February 19, 2025 - The pattern ^[0-9]+$ ensures the string is strictly digits, from start to finish. You can also use \\d as shorthand for digits, so the pattern could be "^\\d+$" instead. That’s usually more readable.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Regular_expressions
Regular expressions - JavaScript | MDN
This allows you to do new RegExp(RegExp.escape("a*b")) to create a regular expression that matches only the string "a*b".
🌐
DigitalOcean
digitalocean.com › community › tutorials › regular-expression-in-java-regex-example
Regular Expression in Java - Java Regex Example | DigitalOcean
August 3, 2022 - Since java regular expression revolves around String, String class has been extended in Java 1.4 to provide a matches method that does regex pattern matching. Internally it uses Pattern and Matcher java regex classes to do the processing but obviously it reduces the code lines.
🌐
Oracle
oracle.com › java › technical details
Regular Expressions and the Java Programming Language
You can use the java.util.regex package to find, display, or modify some or all of the occurrences of a pattern in an input sequence. The simplest form of a regular expression is a literal string, such as "Java" or "programming." Regular expression matching also allows you to test whether a ...
🌐
Regex Generator
regex-generator.olafneumann.org
Regex Generator - Creating regex is easy again!
A tool to generate simple regular expressions from sample text. Enable less experienced developers to create regex smoothly.
🌐
Coderanch
coderanch.com › t › 446190 › java › regex-Find-EXACT-characters-String
[regex help]Find EXACT characters in a String. (Beginning Java forum at Coderanch)
May 20, 2009 - What this regexp does is to check whether any of the characters w, a, t and i occurs anywhere in the string - which w, a and t do, so there's a match. If you want to check that the complete string consists of nothing but those characters, then you need to a) specify that the complete string should be matched, and b) that you want to match more than a single character. Read the java.util.regex.Pattern javadocs about the special characters "^", "$" and "*".
🌐
Reddit
reddit.com › r/learnjava › validating a string using regex
r/learnjava on Reddit: Validating a string using regex
January 1, 2024 -

Hi,

I have written a code to validate the string using regex by following the code at:

regex code for alphabetical string

My regex code is in the following function:

private void CheckIfInputValid(String input, String regex){ 
    String s; //for(int i=0; i<4; ++i) { 
    Pattern pattern  = Pattern.compile(regex); 
    s = input.trim(); Matcher matcher = pattern.matcher(s); 
    JOptionPane.showMessageDialog(null, "Input "+s+" is valid " + String.valueOf(matcher.matches()));//}
}

I have also created a form having a text box and a submit button. In the text box I am inputting a string like: “abacde”. The input is a non-numerical text-based string. The code of submit button is:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    //TODO add your handling code here: 
    StringstrAccName= jTF1.getText();
    String strInput[] = new String[5];
    strInput[0]= strAccName;
    String regex = "[a-zA-Z]";
    CheckIfInputValid(strInput[0], regex);
}

I am getting a false value for matcher.matches().

Somebody please guide me what is the problem with my regex.

Top answer
1 of 4
2
The pattern you specified, [a-zA-Z], will only match against individual characters. The Matcher returned by pattern.matcher() tells you if the pattern matches the entire string. Any string with multiple characters won't match this pattern.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Reddit
reddit.com › r/learnprogramming › how to use java regex?
r/learnprogramming on Reddit: How to use Java Regex?
December 24, 2012 -

I have a problem where I am supposed to get different values from a text file. The problem states: "Use Scanner and an appropriate regular expression."

A line in the text file looks like: "Name=Bob,WaitTime=2990,Rings=3"

I've so far been able to create a scanner and use a while loop(While file.hasNextLine()) to run through the lines of the text file and store them as a String.

I have used the split method to split the string at the ',' character - String[] tokens = inputLine.split(",");

Now what?

How can I get the specific pieces of the string that I want? I.E. how can I parse the name string and store it, how can I parse the waitTime as a long, and how can I parse the rings as an int?

So for this example I'd be able to have: "Bob" 2990 and 3 all parsed and stored in appropriate variables.

Thanks in advance. Edit:Spelling