Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regular expression

Tags:

java

regex

Can anyone please help me do the following in a java regular expression?

I need to read 3 characters from the 5th position from a given String ignoring whatever is found before and after.

Example : testXXXtest

Expected result : XXX

like image 671
javaagn Avatar asked Dec 06 '11 19:12

javaagn


4 Answers

You don't need regex at all.

Just use substring: yourString.substring(4,7)

Since you do need to use regex, you can do it like this:

Pattern pattern = Pattern.compile(".{4}(.{3}).*");
Matcher matcher = pattern.matcher("testXXXtest");
matcher.matches();
String whatYouNeed = matcher.group(1);

What does it mean, step by step:

.{4} - any four characters

( - start capturing group, i.e. what you need

.{3} - any three characters

) - end capturing group, you got it now

.* followed by 0 or more arbitrary characters.

matcher.group(1) - get the 1st (only) capturing group.

like image 188
Goran Jovic Avatar answered Oct 21 '22 05:10

Goran Jovic


You should be able to use the substring() method to accomplish this:

string example = "testXXXtest";
string result = example.substring(4,7);
like image 36
Rion Williams Avatar answered Oct 21 '22 04:10

Rion Williams


This might help: Groups and capturing in java.util.regex.Pattern.

Here is an example:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Example {
  public static void main(String[] args) {
    String text = "This is a testWithSomeDataInBetweentest.";
    Pattern p = Pattern.compile("test([A-Za-z0-9]*)test");
    Matcher m = p.matcher(text);
    if (m.find()) {
      System.out.println("Matched: " + m.group(1));
    } else {
      System.out.println("No match.");
    }
  }
}

This prints:

Matched: WithSomeDataInBetween

If you don't want to match the entire pattern rather to the input string (rather than to seek a substring that would match), you can use matches() instead of find(). You can continue searching for more matching substrings with subsequent calls with find().

Also, your question did not specify what are admissible characters and length of the string between two "test" strings. I assumed any length is OK including zero and that we seek a substring composed of small and capital letters as well as digits.

like image 3
Adam Zalcman Avatar answered Oct 21 '22 05:10

Adam Zalcman


You can use substring for this, you don't need a regex.

yourString.substring(4,7);

I'm sure you could use a regex too, but why if you don't need it. Of course you should protect this code against null and strings that are too short.

like image 1
mkro Avatar answered Oct 21 '22 03:10

mkro