Better way to detect if a string contains multiple words
Editors note: Despite being heavily upvoted and accepted, this does not function the same as the code in the question.
execute
is called on the first match, like a logical OR.
You could use an array:
String[] matches = new String[] {"adsf", "qwer"};
bool found = false;
for (String s : matches)
{
if (input.contains(s))
{
execute();
break;
}
}
This is efficient as the one posted by you but more maintainable. Looking for a more efficient solution sounds like a micro optimization that should be ignored until proven to be effectively a bottleneck of your code, in any case with a huge string set the solution could be a trie.
Check if a string contain multiple specific words
For this, you will need Regular Expressions and the preg_match function.
Something like:
if(preg_match('(bad|naughty)', $data) === 1) { }
The reason your attempt didn't work
Regular Expressions are parsed by the PHP regex engine. The problem with your syntax is that you used the ||
operator. This is not a regex operator, so it is counted as part of the string.
As correctly stated above, if it's counted as part of the string you're looking to match: 'bad || naughty'
as a string, rather than an expression!
Python - Check if a string contains multiple words
Basic implementation
Generally, you use split()
to split a string of words into a list of them. If the list has more than one element, it's True
(i.e. you could print yes)
def contains_multiple_words(s):
return len(s.split()) > 1
Punctuation support
To support punctuation etc as well, you can split on a regular expression, via the re
module's split command:
import re
def contains_multiple_words(s):
return len(re.compile('\W').split(s)) > 1
The regular expression character class \W
means any single non-word character, e.g. punctuation or spaces (see the Python regex syntax guide for details).
Thus, splitting on this instead of just space (the default in the first example) allows for a more realistic idea of "words".
How to check if a string contains multiple words on different locations
If you want to know the length of the match, e.g. using regex:
var str = "There idea";
var pattern = new RegExp("\\b" + str.replace(/ +/g, "\\b.*\\b") + "\\b", "i")
console.log(pattern)
var strings = [
"There is this one thing that I'm trying to do but I have no idea how",
"I really have no clue how too fix it",
"Hopefully maybe someone can help me"
]
for( i=0; i < strings.length; i++ )
if( res=strings[i].match(pattern) )
console.log( res[0], res[0].length )
How to identify the string where it contains multiple words
Here's one approach, which also works for multiple words:
words = ['cat', 'mouse']
m = pd.concat([df.Column.str.lower().str.contains(w) for w in words], axis=1).all(1)
df.loc[m,:]
Column
0 Cat and mouse are the born enemies
Go: how to check if a string contains multiple substrings?
You can write your own utility function using strings.Contains()
that can work for multiple sub-strings.
Here's an example that returns Boolean (true
/false
) in case of complete / partial match and the total number of matches:
package main
import (
"fmt"
"strings"
)
func checkSubstrings(str string, subs ...string) (bool, int) {
matches := 0
isCompleteMatch := true
fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs)
for _, sub := range subs {
if strings.Contains(str, sub) {
matches += 1
} else {
isCompleteMatch = false
}
}
return isCompleteMatch, matches
}
func main() {
isCompleteMatch1, matches1 := checkSubstrings("Hello abc, xyz, abc", "abc", "xyz")
fmt.Printf("Test 1: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch1, matches1)
fmt.Println()
isCompleteMatch2, matches2 := checkSubstrings("Hello abc, abc", "abc", "xyz")
fmt.Printf("Test 2: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch2, matches2)
}
Output:
String: "Hello abc, xyz, abc", Substrings: [abc xyz]
Test 1: { isCompleteMatch: true, Matches: 2 }
String: "Hello abc, abc", Substrings: [abc xyz]
Test 2: { isCompleteMatch: false, Matches: 1 }
Here's the live example: https://play.golang.org/p/Xka0KfBrRD
Check if one of multiple words exists in the string?
Simply checking using preg_match()
, you can add many different words in the pattern, just use a separator |
in between words.
The following will match partial words, so larger words like pit
, testify
, itinerary
will be matched. The pattern is also case-sensitive, so It
and Test
will not be matched.
$str = "it is a test";
if (preg_match("/it|test/", $str))
{
echo "a word was matched";
}
Sorry, I didn't know that you were dealing with other languages, you can try this:
$str = "你好 abc efg";
if (preg_match("/\b(你好|test)\b/u", $str))
{
echo "a word was matched";
}
I also need to mention that \b
means word boundary, so it will only matches the exact words.
Check if multiple strings exist in another string
You can use any
:
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any([x in a_string for x in matches]):
Similarly to check if all the strings from the list are found, use all
instead of any
.
Javascript - How to check if a string contains multiple substrings in one condition
I can only think of this:
'use strict';
String.prototype.includes = function (...args) { return args.filter(str => this.indexOf(str) > -1).length === args.length;};
var str = 'initcall7773107b-7273-464d-9374-1bff75accc15TopCenter';if(str.includes('initcall', 'TopCenter')) { console.log('Do something...');}
Related Topics
Get Code Line and File That's Executing the Current Function in PHP
How to Load View from Alternative Directory in Laravel 4
HTML into PHP Variable (HTML Outside PHP Code)
Is This the Correct Way to Send Email with PHP
How to Retrieve All Variables from a Twig Template
PHP Exec() Is Not Executing the Command
Where Exactly Do I Put a Session_Start
PHP Checkbox Set to Check Based on Database Value
Orm/Dao/Datamapper/Activerecord/Tablegateway Differences
Storage in Laravel Says Symlink - No Such File
How Is Annotation Useful in PHP
How to Send Laravel Error Responses as JSON
Install Yii2 Extension Manually Without Using Composer
Nohup:Ignoring Input and Appending Output to 'Nohup.Out'
This Is the .Htaccess Code in Wordpress. Can Someone Explain How It Works
How to Pass a Parameter Like Title, Summary and Image in a Facebook Sharer Url