UI Bakery RegEx Library
About UI Bakery
Try UI Bakery for Free ↗
RegEx library
Email regex Java
Phone number regex Java
IP address regex Java
Date regex Java
URL regex Java
Numbers only regex (digits only) Java
UUID regex Java
Regex match words Java
ZIP code regex Java
GUID regex Java
Password regex Java
HTML regex Java
SSN regex Java
XML regex Java
Mac address regex Java
Street address regex Java

Regex match words Java

This regular expression can be used to validate that a given string contains only characters in it or extract two words from a given string.

Discover UI Bakery – an intuitive visual internal tools builder. Try it now!

JavaScript
Python
Java
C#
PHP

Simple word match

The regular expression to match only words looks like this (including compound words):

Pattern.compile("^\\b(?:\\w|-)+\\b$")
Test it!
/^\b(?:\w|-)+\b$/

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate word
        boolean isMatch = Pattern.compile("^\\b(?:\\w|-)+\\b$")
               .matcher("word")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract words from a string
        String[] matches = Pattern.compile("\\b(?:\\w|-)+\\b")
                          .matcher("Hello, world!")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [Hello,world]
    }
}

‍

Test it!

True

False

Enter a text in the input above to see the result

Test it!

True

False

Enter a text in the input above to see the result

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Try UI Bakery ↗