-1

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 ?

Matt
  • 13,445
  • 23
  • 82
  • 120
Arnaud Dms
  • 1
  • 1
  • 2

2 Answers2

1
  1. Create a Pattern java.util.regex.Pattern that matches your conditions.
  2. Generate a Matcher java.util.regex.Matcher that handles the input String
  3. let the Matcher find the desired value (by using Matcher.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) );
}
Martin Frank
  • 3,238
  • 1
  • 25
  • 41
Oreste Viron
  • 3,002
  • 3
  • 17
  • 30
  • Thank you this works ! :) From this regex : ("size=\\\"([A-Za-z0-9]{2})\\\"") A last question : how to allow all characters and without specify "{2}" ? Thank you very much everyone ! :) – Arnaud Dms May 04 '16 at 10:36
  • I tried but i can't find how to allow all characteres. Any idea ? :) – Arnaud Dms May 04 '16 at 11:46
  • Hello, Any char is "." The {2} is here to indicate you must have 2 char between your comas. So : `[A-Za-z0-9]{2}` Is equivalent to : `[A-Za-z0-9][A-Za-z0-9]` I recommand you to read some tuto about regular expressions : https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ You can use this site to help you for the beginning : https://www.debuggex.com/ – Oreste Viron May 04 '16 at 12:14
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

http://ideone.com/FqMuTA

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 quote

You can find more info on regex here

Community
  • 1
  • 1
riteshtch
  • 8,189
  • 4
  • 19
  • 35