DT7
DT7

Reputation: 1609

Checking if string starts with _ or a number (0-9)

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

Answers (4)

Rogue
Rogue

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

Mirko Klemm
Mirko Klemm

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

jpvee
jpvee

Reputation: 973

Try the regular expression [_0-9](.*) instead of _(.*).

Upvotes: 3

anubhava
anubhava

Reputation: 785256

This should work:

 legacyId.matches("^[_0-9].*$")

Upvotes: 3

Related Questions