gpt4 book ai didi

java - 正则表达式 : Find mismatched point (or char index)

转载 作者:搜寻专家 更新时间:2023-10-31 19:57:53 24 4
gpt4 key购买 nike

我是正则表达式的初学者。当我们使用正则表达式验证字符串时,有没有办法找到不匹配的点或字符索引?我在 Java 中使用 RegEx 来验证字符串。
我只需要找到第一个不匹配的索引。
更新
请考虑这样的例子。
正则表达式:^\d{9}[VX]$
接受的字符串:547812375X
错误字符串:547A12375X

在错误的字符串中有 A 而不是 8。我需要找到不匹配的索引,因为这里是 4。索引处的字符对于 RegEx 不匹配。

最佳答案

我认为这段代码可能会做你想做的事:

package so7783938;

import static org.junit.Assert.assertEquals;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class RegexFailureTest {

public static int firstFailurePoint(Pattern regex, String str) {
for (int i = 0; i <= str.length(); i++) {
Matcher m = regex.matcher(str.substring(0, i));
if (!m.matches() && !m.hitEnd()) {
return i - 1;
}
}
if (regex.matcher(str).matches()) {
return -1;
} else {
return str.length();
}
}

@Test
public void testSimple() {
Pattern abc = Pattern.compile("abc");
assertEquals(0, firstFailurePoint(abc, ""));
assertEquals(1, firstFailurePoint(abc, "a"));
assertEquals(2, firstFailurePoint(abc, "ab"));
assertEquals(-1, firstFailurePoint(abc, "abc"));
assertEquals(3, firstFailurePoint(abc, "abcd"));
assertEquals(3, firstFailurePoint(abc, "abcdefghi"));
assertEquals(1, firstFailurePoint(abc, "aaa"));
assertEquals(2, firstFailurePoint(abc, "abb"));
}

@Test
public void testAlternative() {
Pattern regex = Pattern.compile("hello|world");
assertEquals(0, firstFailurePoint(regex, "x"));
assertEquals(-1, firstFailurePoint(regex, "hello"));
assertEquals(-1, firstFailurePoint(regex, "world"));
assertEquals(3, firstFailurePoint(regex, "hel"));
assertEquals(5, firstFailurePoint(regex, "hello kitty"));
assertEquals(3, firstFailurePoint(regex, "help me"));
assertEquals(3, firstFailurePoint(regex, "worse is better"));
}

@Test
public void testExample() {
Pattern regex = Pattern.compile("^\\d{9}[VX]$");
assertEquals(-1, firstFailurePoint(regex, "547812375X"));
assertEquals(3, firstFailurePoint(regex, "547A12375X"));
}

}

关于java - 正则表达式 : Find mismatched point (or char index),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7783938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com