[英]Regex for verifying content between tags in XML
我正在嘗試使用正則表達式來驗證XML文件中的內容。 我嘗試了以下方法。
XML檔案1:
<start>
<hi>2dsds</hi>
<expected xmlns="sw2223" xmlns=\"\">123</expected>
<bye>2dsds</bye>
XML檔案2:
<start>
<hi>2dsds</hi>
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
<bye>2dsds</bye>
在這兩個XML文件中,我擔心字段<expected>
和<Somethingexpected>
之間的內容。 我希望該內容之間的每個字段都是數字。
有效內容:
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
<Expected xmlns=\"\">123</Expected>
<expected xmlns=\"\">123</expected>
無效的內容:
<Somethingexpected xmlns="sw2223" xmlns=\"\">123a</Somethingexpected>
<Expected xmlns=\"\">avbv 123</Expected>
<expected xmlns=\"\">**(***</expected>
除了標簽之間的數字(甚至沒有空格),我不需要其他任何東西
我嘗試使用這些正則表達式:
if(String.matches(".*<.*[eE]xpected.*?>.*[a-zA-Z].*<.*") ||
String.matches(".*<.*[eE]xpected.*?>.*[^0-9].*<.*"))
return invalid;
else
return valid;
輸入1:
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
輸入2:
<start>
<hi>2dsds</hi>
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected>
<bye>2dsds</bye>
對於輸入1,這表示有效 。 輸入2表示無效
我不確定我要去哪里錯。 誰能糾正我的正則表達式?
嘗試這個
boolean mathes = str.matches(".*<(Expected|expected|Somethingexpected).*?>\\d+</\\1>.*");
<Somethingexpected xmlns="sw2223" xmlns=\"\">123</Somethingexpected> <Somethingexpected xmlns="sw2223" xmlns=\"\">123a</Somethingexpected>
在這種情況下,我期望結果會失敗,因為其中一個標簽之間存在123a。 但是測試通過了,因為它發現第一個是有效的,因為它之間有123。。因此,我想知道在這種情況下我是否應該使用正則表達式,還是有替代方法..謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.