Java how to use pattern matcher using regular expressions to find certain string

StackOverflow https://stackoverflow.com/questions/22301286

  •  12-06-2023
  •  | 
  •  

Question

I am not familiar with Patterns & matchers, and I am pretty stuck with this problem.

I have a string that I would like to manipulate in Java. I understand that I have to use

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
     String found = m.group(1).toString();
}

But in my string, let's say I have the following examples:

String in = "test anything goes here [A#1234|567]"; //OR
String in = "test anything goes here [B#1234|567]"; //OR
String in = "test anything goes here [C#1234|567]";

I want to find [A# | ] or [B# | ] or [C# | ] in the string, how do I use the regex to find the expression?

Était-ce utile?

La solution

Use [ABC]# in your regex to match your expression.

Pattern p = Pattern.compile("(\\[[ABC]#.*?\\])");

If the fields are digit then you can safely use \d+

Pattern p = Pattern.compile("(\\[[ABC]#\\d+\\|\\d+\\])");

Autres conseils

I'd use a simple Pattern as in the following example:

String[] in = { "test anything goes here [A#1234|567]",
            "test anything goes here [B#1234|567]",
            "test anything goes here [C#1234|567]" };

    Pattern p = Pattern.compile("\\[[A-Z]#\\d+\\|\\d+\\]");
    for (String s: in) {
        Matcher m = p.matcher(s);
        while (m.find()) {
            System.out.println("Found: " + m.group());
        }
    }
}

Output

Found: [A#1234|567]
Found: [B#1234|567]
Found: [C#1234|567]

I'm assuming here that your Pattern has specific restrictions:

  • Starts with [
  • Followed by one upper-case non-accented letter
  • Followed by #
  • Followed by any number of digits
  • Followed by |
  • Followed by any number of digits
  • Followed by ]

Try:

Pattern p = Pattern.compile("(\\[[A-Z]#.*\\])");

If you want to match any capital A through Z. Unclear if you want all the data between [] though.

My solution:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Some {
    public static void main(String[] args) throws java.lang.Exception {
        String[] in = {
            "test anything goes here [A#1234|567]",
                "test anything goes here [B#1234|567]",
                "test anything goes here [C#1234|567]"
        };

        Pattern p = Pattern.compile("\\[(.*?)\\]");
        for (String s: in ) {
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println("Found: " + m.group().replaceAll("\\d", ""));
            }
        }

    }
}

This uses your original regex.

Demo: http://ideone.com/4Z5oYD

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top