Terrails
Terrails

Reputation: 77

Get a specific word out of a String with regex

I have an String

String string = "-minY:50 -maxY:100 -minVein:8 -maxVein:10 -meta:0 perChunk:5;";

And I want to somehow get the -meta:0 out of it with regex (replace everything except -meta:0), I made an regex which deletes -meta:0 but I can't make it delete everything except -meta:0 I tried using some other regex but it was ignoring whole line when I had -meta:[0-9] in it, and like you can see I have one line for everything. This is how it has been deleting -meta:0 from the String:

String meta = string.replaceAll("( -meta:[0-9])", "");
System.out.println(meta);

I just somehow want to reverse that and delete everything except -meta:[0-9]

I couldn't find anything on the page about my issue because everything was ignoring whole line after it found the word, so sorry if there's something similar to this.

Upvotes: 1

Views: 81

Answers (2)

SomeDude
SomeDude

Reputation: 14238

As I understand your requirement you want to :

a) you want to extract meta* from the string

b) replace everything else with ""

You could do something like :

String string = "-minY:50 -maxY:100 -minVein:8 -maxVein:10 -meta:0 perChunk:5;";


Pattern p = Pattern.compile(".*(-meta:[0-9]).*");
Matcher m = p.matcher(string);

if ( m.find() )
{
    string = string.replaceAll(m.group(0),m.group(1));

    System.out.println("After removal of meta* : " + string);
}

What this code does is it finds meta:[0-9] and retains it and removes other found groups

Upvotes: 1

anubhava
anubhava

Reputation: 786091

You should be capturing your match in a captured group and use it's reference in replacement as:

String meta = string.replaceAll("^.*(-meta:\\d+).*$", "$1");
System.out.println(meta);
//=> "-meta:0"

RegEx Demo

Upvotes: 2

Related Questions