bvitaliyg
bvitaliyg

Reputation: 3245

Java Regex: find a match only at the beginnings of words

For example, I have a set of the strings:

"Abc zcf",
"Abcd zcf",
"Zcf Abc",
"Zcf Abcd",
"Test ez",
"Rabc Jabc"

How to find in this set strings which any word begin at "abc" characters? In my example it would be strings

"Abc zcf",
"Zcf Abc",
"Abcd zcf",
"Zcf Abcd"

Upvotes: 0

Views: 138

Answers (4)

Boris the Spider
Boris the Spider

Reputation: 61128

You need to match anything, followed by a word boundary, followed by abc. You also want to do this in a case-insensitive way. The pattern

(?i).*\\babc.*

Will work. A quick example

public static void main(String[] args) throws Exception {
    final Pattern pattern = Pattern.compile("(?i).*\\babc.*");

    final String[] in = {
        "Abc zcf",
        "Abcd zcf",
        "Zcf Abc",
        "Zcf Abcd",
        "Test ez",
        "Rabc Jabc"};

    for (final String s : in) {
        final Matcher m = pattern.matcher(s);
        if (m.matches()) {
            System.out.println(s);
        }
    }
}

Output:

Abc zcf
Abcd zcf
Zcf Abc
Zcf Abcd

EDIT

Further to @fge's comments about matching the whole pattern here is a neater way of searching for the pattern in the String.

public static void main(String[] args) throws Exception {
    final Pattern pattern = Pattern.compile("(?i)(?<=\\b)abc");

    final String[] in = {
        "Abc zcf",
        "Abcd zcf",
        "Zcf Abc",
        "Zcf Abcd",
        "Test ez",
        "Rabc Jabc"};

    for (final String s : in) {
        final Matcher m = pattern.matcher(s);
        if (m.find()) {
            System.out.println(s);
        }
    }
}

This says find abc that is preceded by \b - i.e. the word boundary. The output is the same.

Upvotes: 3

fge
fge

Reputation: 121702

You have to use a Pattern:

final Pattern p = Pattern.compile("\\bAbc");

// ...

if (p.matcher(input).find())
    // match

FYI, \b is the word anchor. Java's definition for a word character is the underscore, a digit or a letter.

Upvotes: 6

TroyAndAbed
TroyAndAbed

Reputation: 301

You can use:

if( maChaine.startWith("Abc") ) 
{ 

    list.add( maChaine ) ; 
}

Upvotes: 1

Omair Shamshir
Omair Shamshir

Reputation: 2136

Try this regex for your problem:

(^Abc| Abc)

Upvotes: 0

Related Questions