我的字符串由:
组成我需要REGEX来匹配给定的(变量)PREFIX和SUFFIX
示例(前缀= ABCD,后缀= 123456789):
String to match (several possible combinations):
ABCD123456789
abcd123456789
ABCD 123456789
abcd 123456789
ABCD 123 456 789
abcd 123 456 789
123456789
123 456 789
String matches
+--------+-------------------+-------+
| PREFIX | SUFFIX | MATCH |
+--------+-------------------+-------+
| | 123456789 | YES |
| | 123 456 789 | YES |
| | 1 2 3 4 5 6 7 8 9 | YES |
| ABCD | 123 456 789 | YES |
| ABCD | 1 2 3 4 5 6 7 8 9 | YES |
+--------+-------------------+-------+
| | 12345678 | NO |
| | 123 456 7890 | NO |
| ABCD | 12345678 | NO |
| ABCD | 123 456 7890 | NO |
| | 123456789 ABCD | NO |
| AB | 123456789 | NO |
+--------+-------------------+-------+
换句话说:
- 如果存在,前缀必须匹配(不区分大小写),如果不存在则必须为忽略
- 后缀必须匹配(空格必须是忽略!)
等效的JAVA代码将是:
//remove prefix (case insensitive)
STRING.substring(STRING.toUpperCase().startsWith(PREFIX) ? PREFIX.length() : 0).
//remove spaces
replace(" ","").
//match
equals(SUFFIX);
非常感谢。
答案 0 :(得分:3)
首先删除数字后缀中/周围的所有空格:
str.replaceAll(" (?=[\\d ]*$)", "").matches("(?i)(ABCD)?123456789")
匹配您的所有测试用例(并且不匹配您的不匹配)。
答案 1 :(得分:0)
我知道你的问题有一个Java标签,但我不熟悉Java。由于Java和JavaScript有一些相似之处,因此这里有一个JavaScript实现来获取想法。
var rows = [{
prefix: null,
suffix: '123456789',
assert: true
}, {
prefix: null,
suffix: '1123 456 789',
assert: true
}, {
prefix: null,
suffix: '1 2 3 4 5 6 7 8 9',
assert: true
}, {
prefix: 'ABCD',
suffix: '123 456 789',
assert: true
}, {
prefix: 'ABCD',
suffix: '1 2 3 4 5 6 7 8 9',
assert: true
},
{
prefix: null,
suffix: '12345678',
assert: false
}, {
prefix: null,
suffix: '123 456 7890',
assert: false
}, {
prefix: 'ABCD',
suffix: '12345678',
assert: false
}, {
prefix: 'ABCD',
suffix: '123 456 7890',
assert: false
}, {
prefix: null,
suffix: '123456789 ABCD',
assert: false
}, {
prefix: 'AB',
suffix: '123456789',
assert: false
}];
var PREFIX = 'ABCD';
var SUFFIX = '123456789';
var separator = '_';
var regex = new RegExp('^(' + PREFIX.toLowerCase() + ')?' + separator + '.*' + SUFFIX.replace(/\s+/g, '') + '$', 'g');
document.write('<pre>generated regex: ' + regex + '</pre>');
for (var i = 0; i < rows.length; i++) {
regex.lastIndex = 0;
var item = rows[i];
var pre = (item.prefix || '').toLowerCase();
var suf = item.suffix.replace(/\s+/g, '');
var subject = pre + separator + suf;
var result = regex.test(subject);
document.write('<pre class="' + ((result === item.assert) ? 'success' : 'fail') + '">' + pre + ' ' + suf + ', expected: ' + item.assert + ', result: ' + result + '</pre>');
}
&#13;
pre { padding: 5px; }
.success { border: 1px solid green; }
.fail { border: 1px solid red; }
&#13;