Check if an array of string contains a regex string - regex

I need to find if a particular string is included in the string array. I have written the below code and it does the job but is there any groovier way to do this?
boolean isApplePresent = false
randomItemList = ['red apple', 'dog', 'cat']
for(i = 0; i < randomItemList.size(); i++) {
if(randomItemList[i] ==~ ".*apple.*") {
isApplePresent = true
break
}
}
println(isApplePresent) //returns true

As per #barmar's comment I tried using any and this too works.
isApplePresent = randomItemList.any{e-> e ==~ ".*apple.*"}

Related

How to check if String contains only operators and numbers in as3?

How to check if String contains only operators and numbers.
The string which may contains 0-9 and +,-,.,/,*,X,=
For example : 28+30-22*5 = when i check this it should return true. If this contains a character then it will return false.
Can we use regexp for this.
This is totally primitive and straightforward, but it should do the trick:
// A collection of valid characters.
const VALID:String = "0123456789+-*/=X ";
function check(sample:String):Boolean
{
for (var i:int = 0; i < sample.length; i++)
{
// Let's iterate the given String, char by char.
var aChar:String = sample.charAt(i);
// The .indexOf(...) method returns -1 if there's no match.
if (sample.indexOf(aChar) < 0)
{
return false;
}
}
// If we got as far as here, it means
// there's no invalid characters in the sample.
return true;
}
trace(check("28+30-22*5 =")); // true
trace(check("a = 100 * 3 / 10")); // false
Of course you can do it the RegExp way, but it will probably be the same logic, just less readable, more difficult to handle, and not measurably faster.

boolean function returning false even though condition is satisfied to return true in c++. Why?

My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse.
bool is_palindrome(int test){
test_s = to_string(test);
test_length = test_s.length();
for (int i=(test_length + 1); i>=0; i--){
test_s_reverse += test_s[i];
}
if (test_s_reverse == test_s){
return true;
}
else {
return false;
}
}
I created a main function to test results and using input 12321 the program returns false, even though cout for test_s_reverse is = 12321 and test_s = 12321.
What am I doing wrong?
You should use test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can't see if you print them.
The .length() function returns you exactly the number of characters in the string. So you either go with test_length, but you do i>0, or if you go in the loop with i>=0 you go with test_length - 1, so you will be sure that there are no blank characters at the end of new string.
But, if you start with test_length, you will need to edit, since there is no character at test_length position:
test_s_reverse += test_s[i-1];
If you use pure C++ code, it should look like this:
bool is_palindrome(int test){
string test_s = to_string(test);
int test_length = test_s.length();
string test_s_reverse;
for (int i=(test_length); i>0; i--){
test_s_reverse += test_s[i-1];
}
if (test_s_reverse == test_s){
return true;
}
else {
return false;
}
}
If it were up to me, I'd do the job rather differently.
std::string has a constructor to build a string for a pair of iterators. It also supports reverse iterators. As such, you can construct a reversed string a bit more easily like this:
std::string test_s_reversed(test_s.rbegin(), test_s.rend());
...but given how much that simplifies the task, you can boil most of it down to something like this:
bool is_palindrome(std::string const &s) {
return s == std::string(s.rbegin(), s.rend());
}
Implementation for an integer would then be something like this:
bool is_palindrome(int val) {
return is_palindrome(std::to_string(val));
}

Check to see if the letters in a word in another array and return true if all match

I am making a hangman game and I have to check to see that all the letters in the word are all in right array and then only return true. I am stuck at this point as I do not know how to return true once all the letters are in
I have tried different false and true scenarios but they don't seem to be working. The for loop below is what I have tried to do.
// This function returns true if the secret word has been guessed correctly.
// Otherwise, it will return false.
bool iswordcomplete(char secretword[], char rights[]) {
// Task 3. Finish this function
//
// Use a for loop to look at each position of the secret word
//
// If all letters in the secret word is in the rights array,
// return true; otherwise, return false.
//
for (i = 0; i < strlen(secretword); i++) {
if secretword[i] != rights
return false;
return false;
}
}
You can use a bool operator :
bool returned = true; //True by default
for (i = 0; i < strlen(secretword); i++)
{
if (secretword[i] != rights) // | If test returns false, returned is set to false
returned &= false; // | If test returns true, returned stays false if previously set to false
}
return returned;
It should put the value at false when the test is false but will not put it back to true
You are comparing the content of the secretword array cells with the rights array pointer: secretword[i] != rights.
This is not what you want.
You want to compare the cells data: secretword[i] != rights[i]
In order to know if a letter of secretword is in rights, you have to loop over rights for all letters of secretword:
bool iswordcomplete(char secretword[], char rights[]) {
for (int i = 0; i < strlen(secretword); i++) {
bool isInRights = false;
// we loop over all characters of rights. We stop at first match
for (int j = 0; j < strlen(rights) && !isInRights; j++)
{
isInRights = (secretword[i] == rights[j]);
}
if (!isInRights)
{
// We haven't found anything in right, let's stop
return false;
}
}
// If we reach this line, all the characters from secretword are in rights
return true;
}
Ok, I've got two bags full of letters, bags A and B. I want to know if bag A contains the same letters as bag B.
The steps you are following are:
Get a letter from bag A named a. If none are left go to step 4
Check if the letter a is equal to bag B.
If it isn't say both bags don't match.
Say both bags don't match.
Do you by chance see the flaws in your logic? Hint: steps 2 and 4 seem a bit off.
A naive way to solve this problem, but that would actually work would be:
Get a letter from bag A named a. If none are left go to step 4.
Go through all letters in bag B trying to find a match with current a.
If a match is found, go to step 1. If not, both bags don't match. Exit.
Bag A and bag B will contain the same letters only and only if the number of letters in A and B are the same.
You could try to use the <algorithm> library with std::all_of and std::find. Possible solution would be:
bool iswordcomplete(char secretword[], char rights[]) {
char* s_end = secretword + std::strlen(secretword);
char* r_end = rights + std::strlen(rights);
return std::all_of(secretword, s_end, [&rights,&r_end](char ch) {
return std::find(rights, r_end, ch) != r_end;
});
}

Split string by "],["

I know one back slash / can be used to escape some special characters like (, . and double back slash // can be used to escape special characters in a string directly.
I want to split:
"[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]"
by ],[ between each sub array.
What should I do if I want to get all the sub arrays by splitting them to be "[[0,0,1,0,0", "0,0,0,0,0","0,0,0,1,0","1,1,0,1,1", "0,0,0,0,0]]" first.
If you have better idea on how to convert them directly into sub arrays including numbers only like "0,0,1,0,0", "0,0,0,0,0","0,0,0,1,0","1,1,0,1,1", "0,0,0,0,0" that will be even better.
Since both [ and ] at special characters in regex you need to escape them.
you can try with below:
str.split("\\],\\[");
Test code:
String str="[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]";
String[] strs = str.split("\\],\\[");
for(String s:strs){
System.out.println(s);
}
Output result:
[[0,0,1,0,0
0,0,0,0,0
0,0,0,1,0
1,1,0,1,1
0,0,0,0,0]]
If you want to remove the duplicate [[ and ]],just add below codes before split:
str = str.substring(2);
str = str.substring(0, str.length()-2);
Updated answer,if you want to eliminate all the brackets in between and at both ends by regex,you write regex like \[?\[((\d,)+\d) then fetch the first group of each match record data, below is the code:
String str = "[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]";
String regex = "\\[?\\[((\\d,)+\\d)";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
The output is
0,0,1,0,0
0,0,0,0,0
0,0,0,1,0
1,1,0,1,1
0,0,0,0,0
Your input is valid JSON, so I suggest using a JSON parser.
The code would look like this:
import javax.json.*;
JsonReader jsonReader = Json.createReader(new StringReader("[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]"));
JsonArray array = jsonReader.readArray();
jsonReader.close();
System.out.println("Array #2: " + array.getJsonArray(1)); // should give [0,0,0,0,0]
System.out.println("Array #3, 4th value: " + array.getJsonArray(2).getInt(3)); // should give 1
If you want the String to convert into a 2d-Array, you can use below functions that takes the String and returns the 2d-Array of ints:
private static int[][] getMatrixFromString(String arrayStrinng) {
String arrayString = arrayStrinng.substring(1, arrayStrinng.length() - 1);
String[] splitMajor = arrayString.split("],");
int rowCount = splitMajor.length, colCount = 0;
int[][] matrix = new int[rowCount][];
for (int row = 0; row < splitMajor.length; row++) {
String[] splitMinor = splitMajor[row].split(",");
if (colCount == 0) {
colCount = splitMinor.length;
matrix = new int[rowCount][colCount];
}
for (int i = 0; i < colCount; i++) {
if (splitMinor[i].startsWith("["))
splitMinor[i] = splitMinor[i].substring(1);
if (splitMinor[i].endsWith("]"))
splitMinor[i] = splitMinor[i].substring(0, splitMinor[i].length() - 1);
matrix[row][i] = Integer.parseInt(splitMinor[i]);
}
}
return matrix;
}

Replace number with repeated characters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I have a string: 8, and I wanted to replace numbers [0-9] with a . that would repeat as many times as the number. What regex string would I use?
e.g.: input string
8
output
........
You can't do this using only regular expressions so you'll have to rely on a language or library feature which allows substitution of matched strings with the result of calling a function with the match as an argument.
In Ruby:
"8".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "........"
"812".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "..........."
"a1b2".gsub(/[0-9]/) { |x| '.' * x.to_i } # => "a.b.."
In JavaScript:
function replaceNumbersWithDots(str) {
return (''+str).replace(/[0-9]/g, function(m) {
var s='', num=parseInt(m, 10);
for (i=0; i<num; i++) { s+= '.'; }
return s;
});
}
replaceNumbersWithDots('8'); // => "........"
replaceNumbersWithDots('812'); // => ".........."
replaceNumbersWithDots('a1b2'); // => "a.b.."
In Java:
public static void main(String args[]) throws Exception {
System.out.println(replaceNumbersWithDots("8")); // => "........"
System.out.println(replaceNumbersWithDots("812")); // => "..........."
System.out.println(replaceNumbersWithDots("a1b2")); // => "a.b.."
}
public static String replaceNumbersWithDots(String s) {
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(s);
StringBuffer buf = new StringBuffer();
while (matcher.find()) {
int x = Integer.parseInt(matcher.group());
matcher.appendReplacement(buf, stringOfDots(x));
}
return buf.toString();
}
public static String stringOfDots(int x) {
String s = "";
for (int i=0; i<x; i++) { s += "."; }
return s;
}
This can't be done with standard regular expressions alone. As #m.buettner points out, you can in certain languages specify a function that processes the replacement. For example, with Python
>>> import re
>>> s = '8'
>>> re.sub(r'\d', lambda m: '.'*int(m.group()), s)
'........'
But maybe you don't even need a regex? Since you're only looking for single-character matches (namely \d), you can perhaps do something like this:
Initialize some sort of string buffer to hold the resultant string
Loop over the characters of your input string
If the character is a digit, parse it as an integer and append that many .s to your buffer.
Otherwise, append the character itself to your buffer.
Here's an implementation of this in Java:
String s = "8";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
int n = c - '0';
for (int i = 0; i < n; i++)
sb.append('.');
} else {
sb.append(c);
}
}
System.out.println(sb);
........
AS you didn't provide a lang, i made an exemple of solving it in php
$tr = array();
foreach(range(0, 9) as $nr)
{
$tr[$nr] = str_repeat('.', $nr);
}
echo strtr("Hello 8", $tr);
// Gives: "Hello ........"