How to convert xsd: pattern to java regex

As I know, and I used very little java regex, is there a method (or tool) to convert the xsd: pattern control to java regex?

My xsd: template is as follows:

<xsd:simpleType name="myCodex">
<xsd:restriction base="xsd:string">
 <xsd:pattern value="[A-Za-z]{6}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9A-Za-z]{3}[A-Za-z]{1}" />
 <xsd:pattern value="[A-Za-z]{6}[0-9LMNPQRSTUV]{2}[A-Za-z]{1}[0-9LMNPQRSTUV]{2}[A-Za-z]{1}[0-9LMNPQRSTUV]{3}[A-Za-z]{1}" />
 <xsd:pattern value="[0-9]{11,11}" />
</xsd:restriction>
</xsd:simpleType>
+4
source share
1 answer

You can load the XSD into Java and extract the expressions. Then you can use them in methods .matches()or create objects Patternif you intend to use them repeatedly.

First you need to load the XML into a Java program (I named it CodexSchema.xsd):

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document source = builder.parse(new File("CodexSchema.xsd"));

XPath , ( , , ). XPath, :

XPathFactory xPathfactory = XPathFactory.newInstance();
String typeName = "myCodex";
String xPathRoot = "//*[local-name()='simpleType'][@name='"+typeName+"']/*[local-name()='restriction']/*[local-name()='pattern']";
XPath patternsXPath = xPathfactory.newXPath(); // this represents the NodeList of <xs:pattern> elements

, org.xml.dom.NodeList, <xs:pattern>.

NodeList patternNodes = (NodeList)patternsXPath.evaluate(xPathRoot, source, XPathConstants.NODESET);

value. :

public List<Pattern> getPatterns(NodeList patternNodes) {
    List<Pattern> expressions = new ArrayList<>();
    for(int i = 0; i < patternNodes.getLength(); i++) {
        Element patternNode = (Element)patternNodes.item(i);
        String regex = patternNode.getAttribute("value");
        expressions.add(Pattern.compile(regex));
    }
    return expressions;
}

Pattern. String.

Java, :

for(Pattern p : getPatterns(patternNodes)) {
    System.out.println(p);
}

:

Pattern pattern3 = getPatterns(patternNodes).get(2);

Matcher matcher = pattern3.matcher("47385628403");
System.out.println("test1: " + matcher.find());  // prints `test1: true`

System.out.println("test2: " + "47385628403".matches(pattern3.toString()));  // prints `test2: true`
+1

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


All Articles