[英]Java regular expressions for specific name\value format
I'm not familiar yet with java regular expressions. 我对Java正则表达式还不熟悉。 I want to validate a string that has the following format:
我想验证具有以下格式的字符串:
String INPUT = "[name1 value1];[name2 value2];[name3 value3];";
namei and valuei are Strings should contain any characters expect white-space. namei和valuei是字符串,应包含除空格以外的任何字符。
I tried with this expression: 我尝试使用以下表达式:
String REGEX = "([\\S*\\s\\S*];)*";
But if I call matches() I get always false even for a good String. 但是,如果我调用matches(),即使获得一个好的String,我也总是会得到false。
what's the best regular expression for it? 最好的正则表达式是什么?
This does the trick: 这可以解决问题:
(?:\[\w.*?\s\w.*?\];)*
If you want to only match three of these, replace the *
at the end with {3}
. 如果只想匹配其中三个,请用
{3}
替换末尾的*
。
Explanation: 说明:
(?:
: Start of non-capturing group (?:
非捕获组的开始
\\[
: Escapes the [
sign which is a meta-character in regex. \\[
:转义[
符号,它是正则表达式中的元字符。 This allows it to be used for matching. 这使其可以用于匹配。
\\w.*?
: Lazily matches any word character [az][AZ][0-9]_
. :懒惰地匹配任何单词字符
[az][AZ][0-9]_
。 Lazy matching means it attempts to match the character as few times possible, in this case meaning that when will stop matching once it finds the following \\s
. 延迟匹配表示它尝试尽可能少地匹配字符,在这种情况下,这意味着当找到以下
\\s
时将停止匹配。
\\s
: Matches one whitespace \\s
:匹配一个空格
\\]
: See \\[
\\]
:请参见\\[
;
: Matches one semicolon :匹配一个分号
)
: End of non-capturing group )
:非捕获组的结尾
*
: Matches any number of what is contained in the preceding non-capturing group. *
:匹配前面的非捕获组中包含的任何数量。
You should escape square brackets. 您应该使用方括号。 Also, if your aim is to match only three, replace
*
with {3}
另外,如果您的目标是仅匹配三个,请将
*
替换为{3}
(\[\\S*\\s\\S*\];){3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.