有人能帮我做字符串验证吗?我试图找到解决办法,但没有人满意。我有一只狗/猫/房子,1/老鼠/鸟,1/兔子。
我需要检查单词(用逗号)后是否有鸟,是否有数字。在我的情况下,有时我收到uri与数字:“鸟,1”,有时与字:“鸟,福”。谢谢你的建议。
发布于 2022-07-15 07:59:27
正如@Federico klez Culloca和@The fourth bird建议的那样,您可以使用正则表达式(正则表达式,\\bbird,(?:[1-9]|1[0-9]|20)\\b),但是一些安全扫描不喜欢正则表达式。在任何情况下,其他(纯Java)解决方案将是:
在用户添加了更多条件后更新了答案。
would look for range 1, 2 .. 20 (01, 02 would return false).
public static boolean isNumber() {
// you can parametrize these 2
String input = "/dog/cat/house,1/mouse/bird,10/rabbit.";
String strOfInterest = "/bird,";
boolean isStringEndingInLT20 = false;
int indxOfInterest = input.indexOf("/bird,") + strOfInterest.length();
char c1 = input.charAt(indxOfInterest);
char c2 = input.charAt(indxOfInterest + 1);
int i1 = Character.getNumericValue(input.charAt(indxOfInterest));
if (Character.isDigit(c1) && Character.isDigit(c2)) {
int num = Integer.parseInt("" + c1 + c2);
if ((i1 > 0) && (num >= 1) && (i1 <= 20)) isStringEndingInLT20 = true;
} else if (Character.isDigit(c1)) {
if ((i1 >= 1) && (i1 <= 9)) isStringEndingInLT20 = true;
}
return isStringEndingInLT20;
}注意:我个人讨厌这些冗长的解决方案,我更喜欢1行REGEX。尽量避免使用regex。我避免regex的唯一情况是当它成为性能瓶颈和/或引起安全问题时。
发布于 2022-07-15 08:52:29
这是一个实用的算法,可以指定关键字!前提是包含参数的有效性与您的描述一致。
关键字,(允许空格)123/
public static void main(String[] args) throws IOException {
String contains = "/dog/cat/house,1/mouse/bird,a/rabbit";
FreeTest f = new FreeTest();
boolean has = f.hasNumber(contains, "bird");
System.out.println(has);
}
/**
* Check if string contains number after specific word
*
* @param contains string contains
* @param key the specific word (without comma)
* @return yes or not
*/
public boolean hasNumber(String contains, String key) {
int commaIndex = contains.indexOf(',', contains.indexOf(key));
int startIndex = commaIndex + 1;
boolean hasNumber = true;
while (true) {
char c = contains.charAt(startIndex++);
if (c == '/') break; // exit
if (c != ' ') {
hasNumber = Character.isDigit(c);
}
}
return hasNumber;
}https://stackoverflow.com/questions/72990694
复制相似问题