anonymous
anonymous

Reputation: 503

How to write a regex in java to check whether a string contains two chars space and three integers?

I have a string String myString = "abc,QWAB 123,cdef";.

How to write regex to check whether my string has AB (space)123. I don't want to consider QW. Also number 123 will be one digit or two digit or three digit, Always it will not be three digit.

Please help.

Upvotes: 0

Views: 64

Answers (4)

mdagis
mdagis

Reputation: 116

This this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Hello world!
 *
 */
public class App {

static String myString = "abc,QWAB 123,cdef";
static String abcPattern = "(AB[\\s]{1}\\d{1,3})";

public static void main(String[] args) {


    Pattern pattern = Pattern.compile(App.abcPattern, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(myString);
    if (matcher.find()) {
        System.out.println(matcher.group());
    } else {
        System.out.println(" No mach found   ");
    }
}

}

Upvotes: 0

SMA
SMA

Reputation: 37023

Try something like:

String myString = "abc,QWAB 123,cdef";
if (myString.matches(".*AB [0-9]{1,3}.*")) {
    System.out.println("Yes it mateched");
} else {
    System.out.println("Hard luck");
}

Upvotes: 0

vks
vks

Reputation: 67968

^[^,]+,AB \d{1,3},.*$

Try this.This should do it.See demo.

https://regex101.com/r/gX5qF3/8

Upvotes: 0

laune
laune

Reputation: 31290

Pattern pat = Pattern.compile( "AB \\d{1,3}" );

Upvotes: 3

Related Questions