df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
df[df['A']=='foo']
OUTPUT:
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
Одним из возможных решений является использование регулярных выражений .
public static boolean isValid(String str) {
// regular expression matches 1 or 2 digit number
Matcher matcher = Pattern.compile("(?<!\\d)\\d{1,2}(?!\\d)").matcher(str);
int sum = 0;
// iterate over all found digits and sum it
while (matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
return sum >= 80 && sum <= 95;
}
Вы должны использовать регулярное выражение для этого вида анализа:
public class Example {
public static void main(String[] args) {
String input = "Hi 57 how are you 30";
System.out.println(process(input));
}
private static boolean process(String input) {
Pattern pattern = Pattern.compile(".*?(\\d+).*?(\\d+)");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
int one = Integer.parseInt(matcher.group(1));
int other = Integer.parseInt(matcher.group(2));
System.out.println(one);
System.out.println(other);
int total = one + other;
return total >= 80 && total <= 95;
}
return false;
}
}
Вывод:
57
30
true [ 115] blockquote>
Вы можете преобразовать строку в массив и проверить, является ли каждый элемент строки (разделенный пробелом) цифрой, протестировав метод Integer.parseInt () для каждого элемента строки. Вот пример ниже:
public static boolean isDig(String theString) {
String[] theStringArray = theString.split(" ");
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int x = 0; x < theStringArray.length; x++) {
String thisString = theStringArray[x];
try {
int num = Integer.parseInt(thisString);
nums.add(num);
}catch(NumberFormatException e) {
continue;
}
}
int total = 0;
for(int num: nums) {
total += num;
}
if(total >= 80 && total <= 95) {
return true;
}
else {
System.out.println(total);
return false;
}
}
Сначала мы разбиваем исходную строку на массив, основанный на пустых местах. Затем мы создаем ArrayList, который добавит к нему каждую цифру в строке. Затем мы создаем цикл for для просмотра каждой отдельной строки в массиве и устанавливаем блок try-catch. Если мы можем преобразовать цифру в int с помощью метода Integer.parseInt (), мы добавим ее в ArrayList. Если нет, мы перехватим исключение и продолжим цикл с помощью оператора continue. Как только мы вырвемся из цикла, мы можем создать переменную под названием «total» и создать еще одну для цикла, чтобы добавить каждую цифру в ArrayList к общей сумме. Если сумма больше / равна 80 и меньше / равна 95, мы вернем True, иначе вернем false. Давайте проверим код:
String digitTest = "There is a digit here: 50 and a digit here 45";
System.out.println(isDig(digitTest));
Числа 50 и 45 должны быть равны 95, и наш результат:
true