Java Regex to see if a String contains %s, %d, %n

Go To StackoverFlow.com

1

So I'm writing my own variation of the toString() method and basically when you call the method you pass in a string and then an argument toString(Object... args). Like so

this.toString("%8s", this.log, "%n%s %s", this.theMap, "%s", this.countIterator());

And from that I use the following code to see if the argument passed in is a regular String or a format String.

if(args[i].getClass().getName() == "java.lang.String") {
  if(args[i].toString().contains("%\\-?[1-9]s?*")) {

    format = args[i].toString();

  } else {

    s += args[i].toString();

  }
}

The args[i].toString().contains("%\\-?[1-9]s?*") regex isn't working, however when I use args[i].toString().matches("%\\-?[1-9]s?*") it works but only for instances of a String with %s or %9s not for instances with %s %9s or %s%s %s. And it also works when I swap the s in the regex with a d or n.

I know your asking why reinvent the wheel, just use String.format(), and I should it's just that I've got this on my mind and can't do anything else until I solve it.

I also tried copying and pasting the java.util.Formatter class'
"%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])" regex but it did the same as above and only worked for %s or %9s.

I also noticed in the Formatter class that the developers used an instance of the Matcher class with an instance of the Patern class and used a for loop to run through a String and match each instance of the pattern and stored it into an ArrayList. I don't really want to do that, I just want to see if the String argument has one instance of %n or %s or %d and from that store it in a String that will be used later in cobination with String.format(format, argument);.

So if anyone could help me that would be awesome!
Thank you for reading this far.

2012-04-05 20:43
by Jonny Henly


2

Try this

Pattern p = Pattern.compile("(%[0-9]*(s|d|n))");
System.out.println("match: " + p.matcher(str).find());

you can store the pattern as a global or static variable and reuse it when you need.

2012-04-05 20:49
by dash1e
Hey that worked really well, thank you so much - Jonny Henly 2012-04-05 21:00
Ads