Question about Java regex

I get a string from a list of arrays:

array.get(0).toString()

gives title = "blabla"

I need a blabla string, so I try this:

Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
System.out.println("Title : " + m.group(0));

Does not work: java.lang.IllegalStateException: No match found

I am also trying:

Pattern p = Pattern.compile("\".*\"");
Pattern p = Pattern.compile("\".*\"");  
Pattern p = Pattern.compile("\\\".*\\\"");

Nothing matches in my program, but ALL templates work on http://www.fileformat.info/tool/regex.htm

Any idea? Thanks in advance.

+3
source share
3 answers

A few points:

Javadoc for Match Group # states:

IllegalStateException - if a match has not yet been attempted, or if the previous match operation failed

m.matches ( ), m.find ( ).

-, m.group(1), m.group(0) - .

, , , (0) , (1), , : "TITLE = (\".*\")"

:

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

import org.junit.Test;

@SuppressWarnings("serial")
public class MatcherTest {

    @Test(expected = IllegalStateException.class)
    public void testIllegalState() {
        List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
        Pattern p = Pattern.compile("(\".*\")");
        Matcher m = p.matcher(array.get(0).toString());
        System.out.println("Title : " + m.group(0));
    }

    @Test
    public void testLegal() {
        List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
        Pattern p = Pattern.compile("(\".*\")");
        Matcher m = p.matcher(array.get(0).toString());
        if (m.find()) {
            System.out.println("Title : " + m.group(1));
        }
    }
}
+8

find() matches() Matcher: . , , .

+6

Do you include double quotation marks (") in the string?

All your regular expressions are escaped and will only match if the line in the list contains double quotation marks.

0
source

Source: https://habr.com/ru/post/1706890/


All Articles