Binoy Babu
Binoy Babu

Reputation: 17139

REGEX : How to escape []?

I'm working on strings like "[ro.multiboot]: [1]". How do I just select 1(it can also be 0) out of this string?

I am looking for a regex in Java.

Upvotes: 0

Views: 126

Answers (2)

Betlista
Betlista

Reputation: 10547

@paxdiablo's regexps are correct, but complete answer for "How do I just select 1(it can also be 0) out of this string?" is:

1. very simple solution

    String input = "[ro.multiboot]: [1]";
    String matched = input.replaceFirst( "^.*\\[ro.multiboot\\].*\\[([01])\\].*$", "$1" );

2. same functionality, more complicated but with better performance

    String input = "[ro.multiboot]: [1]";
    Pattern p = Pattern.compile( "^.*\\[ro.multiboot\\].*\\[([01])\\].*$" );
    Matcher m = p.matcher( input );
    String matched = null;
    if ( m.matches() ) matched = m.group( 1 );

Performance is better because the pattern is compiled just once (for example when you are matching array os such Strings);

Notes:

  • in both examples the group is part of regexps between ( and ) (if not escaped)
  • in Java you have to use \\[, because \[ returns error - it is not correct escape sequence for String

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882028

Usually, you would do something like (assuming 0 and 1 were the only options):

^.*\[([01])\].*$

If you only wanted the value for ro.multiboot, you could change it to something like:

^.*\[ro.multiboot\].*\[([01])\].*$

(depending on how complex any of the non-bracketed stuff is allowed to be).

These would both basically only extract the value between square brackets if it were zero or one, and capture it into a capture variable so you could use it.

Of course, regex is not a world-wide standard, nor are the environments in which you use it. That means it depends a lot on your actual environment how you will actually code this up.


For Java, the following sample program may help:

import java.util.regex.*;

class Test {
    public static void main(String args[]) {
        Pattern p = Pattern.compile("^.*\\[ro.multiboot\\].*\\[([01])\\].*$");
        String str;
        Matcher m;

        str = "[ro.multiboot]: [0]";
        m = p.matcher (str);
        if (m.find()) {
            System.out.println ("str0 has " + m.group(1));
        }

        str = "[ro.multiboot]: [1]";
        m = p.matcher (str);
        if (m.find()) {
            System.out.println ("str1 has " + m.group(1));
        }

        str = "[ro.multiboot]: [2]";
        m = p.matcher (str);
        if (m.find()) {
            System.out.println ("str2 has " + m.group(1));
        }
    }
}

This results in (as expected):

str0 has 0
str1 has 1

Upvotes: 4

Related Questions