Reputation: 1609
My code parses an XML file to look for IDs. But I only need to store the ones starting with _
or some number.
Node legacyNode = (Node) xPath2.evaluate(elem, XPathConstants.NODE);
Element legacyElem = (Element) legacyNode;
if (legacyElem != null) {
String legacyId = legacyNode.getFirstChild().getNodeValue();
if (legacyId.matches("_(.*)")) {
entry.setLegacyID(legacyId);
}
}
if (legacyId.matches("_(.*)"))
checks for IDs starting with _
. I don't know what I should change it to, so it checks for numbers too.
Upvotes: 1
Views: 2839
Reputation: 11483
Why not just substring and compare?:
String sample = /*whatever*/;
String check = sample.substring(0, 1);
if (check.matches("[0-9_]")) {
// starts with number or _
}
Edit based on the comment's suggestion below:
String sample = /*whatever*/;
String check = sample.substring(0, 1);
if ("_1234567890".indexOf(check) != -1) {
// starts with number or _
}
Do note you should check that the string isn't empty/null to start
Upvotes: 2
Reputation: 2068
How about putting the logic into the XPath expression? This may not be faster, but under certain circumstances it may be more elegant.
Upvotes: 0