1

I'm trying to extract a piece of string from a larger string.

Example:

String value;
...etc...
value = someMethod();

// Here value equals a large string text
value;

I want to extract a subset of this string which begins with "path=" and everything after it.

Elaborated Example:

if value equals:

StartTopic topic=testParser, multiCopy=false, required=true, all=false, path=/Return/ReturnData/IRSW2

I want only "path=/Return/ReturnData/IRSW2" so on and so forth.

How could I do this in Java?

This is what I currently have:

if(value.contains("path")) {
    String regexStr = FileUtils.readFileToString(new File("regex.txt"));
    String escapedRegex = StringEscapeUtils.escapeJava(regexStr);
    System.out.println(value.replaceAll(escapedRegex), "$1");
}

This doesn't work! Just outputs the whole string again

Contents of regex.txt:

/path=([^\,]+)/

mosawi
  • 1,283
  • 5
  • 25
  • 48

4 Answers4

1

This should do the trick

String s = "if value=StartTopic topic=testParser, multiCopy=false, required=true, all=false, path=/Return/ReturnData/IRSW2";
String regex= "path=[^\\,]*";

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(s);

if(m.find()) {
    System.out.println(m.group());
}
Till Rohrmann
  • 13,148
  • 1
  • 25
  • 51
1

You can also use:

String regex = "(?<=path=)[^\\,]*";

insted, so you will get only /Return/ReturnData/IRSW2 part.

m.cekiera
  • 5,365
  • 5
  • 21
  • 35
0

Use the function indexOf() to find the index of 'path='

Sygnerical
  • 231
  • 1
  • 3
  • 12
-1
String str = "path=/Return/ReturnData/IRSW2";
System.out.println(str.substring(str.indexOf("path=") + 5));
nLee
  • 1,320
  • 2
  • 10
  • 21