0

I am trying to use regex for verifying contents in an XML file. I have tried the following things.

XML file 1:

<start>
   <hi>2dsds</hi>   
   <expected xmlns="sw2223" xmlns=\"\">123</expected>        
   <bye>2dsds</bye>  

XML file 2:

<start>
   <hi>2dsds</hi>   
   <Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
   <bye>2dsds</bye>  

In these two XML files, I am concerned about the contents between the fields <expected> and <Somethingexpected>. I want each and every field between that content to be numeric.

Valid contents:

<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
<Expected xmlns=\"\">123</Expected>
<expected xmlns=\"\">123</expected>

Invalid contents:

<Somethingexpected xmlns="sw2223" xmlns=\"\">123a</Somethingexpected>
<Expected xmlns=\"\">avbv 123</Expected>
<expected xmlns=\"\">**(***</expected>

I don't need anything other that a number between the tags (not even a space)

I have tried using these regular expressions:

    if(String.matches(".*<.*[eE]xpected.*?>.*[a-zA-Z].*<.*") || 
       String.matches(".*<.*[eE]xpected.*?>.*[^0-9].*<.*"))    
        return invalid;
    else
        return valid; 

Input 1:

<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>

Input 2:

<start>      
    <hi>2dsds</hi>
    <Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
    <bye>2dsds</bye>

For input 1, this says valid. For input 2 it says invalid

I am not sure where I am going wrong. Could anyone correct my regexes?

4

2 回答 2

0
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected> <Somethingexpected xmlns="sw2223" xmlns=\"\">123a</Somethingexpected> 

在这种情况下,我希望结果应该失败,因为其中一个标签之间有 123a。但是测试通过了,因为它发现第一个是有效的,因为它之间有 123.. 因此我想知道在这种情况下我是否应该使用正则表达式,或者是否有替代方法.. 谢谢

于 2013-05-19T23:47:46.057 回答
0

尝试这个

boolean mathes = str.matches(".*<(Expected|expected|Somethingexpected).*?>\\d+</\\1>.*");
于 2013-05-18T02:52:37.443 回答