I need some help because i'm junior in Java and after some research on the web I can't find a solution. So my problem:
String str : size="A4"
I would like to extract 'A4' with a regex by giving the word "size" in the regex. How can I do ?
I need some help because i'm junior in Java and after some research on the web I can't find a solution. So my problem:
String str : size="A4"
I would like to extract 'A4' with a regex by giving the word "size" in the regex. How can I do ?
java.util.regex.Pattern
that matches your conditions. java.util.regex.Matcher
that handles the input StringMatcher.group(group)
).
//1. create Pattern
Pattern p = Pattern.compile("size=\\\"([A-Za-z0-9]{2})\\\"");
//2. generate Matcher
Matcher m = p.matcher(myString);
//3. find value using groups(int)
if(m.find()) {
System.out.println( m.group(1) );
}
import java.util.*;
import java.util.regex.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Matcher m=Pattern.compile("size\\s*=\\s*\"([^\"]*)\"").matcher("size=\"A4\"");
while(m.find())
System.out.println(m.group(1));
}
}
Output:
A4
Regex breakdown:
size\\s*=\\s*\"([^\"]*)\"
size
matches size
literally\\s*=\\s*
matches 0 or more white spaces leading or trailing the
=
sign\"
matches a double quote([^\"]*)
matches 0 or more characters(which is not a double quote
[^\"]
) and remembers the captured text as back-reference 1 i.e
nothing but captured group number 1 used below in the while loop\"
we match the ending double quoteYou can find more info on regex here