Matthew Hooker Matthew Hooker - 4 months ago 5
Android Question

Regex Help: Excluding characters

I've been working on a scripting language used specifically for Tiled Map Editor. Anyways, I've a string "[1]{x: 0, y: 0}". What I want to do is remove everything besides the number 1 using regex with the function replaceAll("regex", "") if possible.


You just need to strip out the leading [ and then everything from ] on, like this:


I'm not a Java expert, but I believe this is the correct syntax:

String str = "[1]{x: 0, y: 0}";
String replaced = str.replaceAll("^\\[|].+$", "");
System.out.println(replaced); // outputs 1

A simpler way to do it would just be to match against \d+, without the global (g) flag