Is stringA in StringB in MATLAB - string

Is there a way to check if a string exists within another string in MATLAB. In python this is done easily with a in b. I do not want indexes or anything like that. I just want to check if its true or not. The answers that I find is "strcmp" or "strfind" and also regexp. regexp returns indexes. strcmp(a, b) does not seem to work. I have a string a = 'ac' and another string b = 'bc_gh_ac'. And want to check if a in b.
Best regards

The answer is indeed strfind. You have to be careful with the order of the parameters which at first seems unusual - the pattern is the second argument, not the first. The following code demonstrates:
a='ac';
b='bc_gh_ac';
strfind(b,a)
If you simply want to test whether the string is present or not then use the isempty function:
if ~isempty(strfind(b,a))
disp('String is present');
end

Related

Replacing a certain part of string with a pre-specified Value

I am fairly new to Puppet and Ruby. Most likely this question has been asked before but I am not able to find any relevant information.
In my puppet code I will have a string variable retrieved from the fact hostname.
$n="$facts['hostname'].ex-ample.com"
I am expecting to get the values like these
DEV-123456-02B.ex-ample.com,
SCC-123456-02A.ex-ample.com,
DEV-123456-03B.ex-ample.com,
SCC-999999-04A.ex-ample.com
I want to perform the following action. Change the string to lowercase and then replace the
-02, -03 or -04 to -01.
So my output would be like
dev-123456-01b.ex-ample.com,
scc-123456-01a.ex-ample.com,
dev-123456-01b.ex-ample.com,
scc-999999-01a.ex-ample.com
I figured I would need to use .downcase on $n to make everything lowercase. But I am not sure how to replace the digits. I was thinking of .gsub or split but not sure how. I would prefer to make this happen in a oneline code.
If you really want a one-liner, you could run this against each string:
str
.downcase
.split('-')
.map
.with_index { |substr, i| i == 2 ? substr.gsub(/0[0-9]/, '01') : substr }
.join('-')
Without knowing what format your input list is taking, I'm not sure how to advise on how to iterate through it, but maybe you have that covered already. Hope it helps.
Note that Puppet and Ruby are entirely different languages and the other answers are for Ruby and won't work in Puppet.
What you need is:
$h = downcase(regsubst($facts['hostname'], '..(.)$', '01\1'))
$n = "${h}.ex-ample.com"
notice($n)
Note:
The downcase and regsubst functions come from stdlib.
I do a regex search and replace using the regsubst function and replace ..(.)$ - 2 characters followed by another one that I capture at the end of the string and replace that with 01 and the captured string.
All of that is then downcased.
If the -01--04 part is always on the same string index you could use that to replace the content.
original = 'DEV-123456-02B.ex-ample.com'
# 11 -^
string = original.downcase # creates a new downcased string
string[11, 2] = '01' # replace from index 11, 2 characters
string #=> "dev-123456-01b.ex-ample.com"

Detect if presence of a character in a string with Lua

I can have two types of string: nxs_flo_dev.nexus orfpdesk.
I want to test if there is a . in the string.
If there is a . I divide the string otherwise I do not do anything.
if(ngx.var.host.contains('.') then
content_by_lua 'ngx.say(ngx.var.host:match("(.-)%."))';
end
Is there a function to do that? Because .contains() doesn't work.
Use match again. Remember to escape the dot with %.:
if ngx.var.host:match('%.') then
If you want to do this inside content_by_lua do
content_by_lua 'if ngx.var.host:match('%.') then ngx.say(ngx.var.host:match("(.-)%.")) end';
Given your edit, this is the simplest solution:
content_by_lua 'ngx.say(ngx.var.host:match("(.-)%.") or ngx.var.host)';

Checking for Item in a List Box Ignoring Case

Having an issue with a bit of code designed to add an email alias to a list box. I have a check built in to ensure the item you attempt to add isn't already in the list, but the check is case sensitive when I don't want it to be. I'm not sure how to make it ignore the case... Here's my code:
Dim ItemToAdd as String = ""
ItemtoAdd = tbxItemtoAdd.Text + "#emaildomain.co.uk"
If Not lbxEmailAliases.Items.Contains(ItemtoAdd) Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If
At the moment if the list box contains johnsmith24#emaildomain.co.uk and you try to add Johnsmith24 (capital J), it will add this successfully, but I don't want it to do that. How do I get it to ignore case?
I've tried changing lbxEmailAliases.Items.Contains(ItemtoAdd) to lbxEmailAliases.Items.Contains(ItemtoAdd, StringComparison.CurrentCultureIgnoreCase) but it's not happy with this as there are too many arguments, it will only take one.
Any ideas please?
If this is a standard WinForm ListBox control, then there is no way to do it without looping through all of the items and checking each one individually. For instance:
Dim found As Boolean = False
For Each item As Object In ListBox1.Items
found = item.ToString().Equals(ItemToAdd, StringComparison.CurrentCultureIgnoreCase)
If found Then
Exit For
End If
Next
If found Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If
However, if you are comfortable with LINQ, you can do it more concisely like this:
If ListBox1.Items.OfType(Of String).Any(Function(item) item.Equals(ItemToAdd, StringComparison.CurrentCultureIgnoreCase)) Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If
Or, as Andy G pointed out, the LINQ Contains method is even easier since it accepts an IEqualityComparer and a stock one which supports case insensitive string comparisons is provided by the framework:
If ListBox1.Items.OfType(Of String).Contains(ItemToAdd, StringComparer.CurrentCultureIgnoreCase) Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If
It should be StringComparer, not StringComparison:
lbxEmailAliases.Items.Contains(ItemtoAdd, StringComparer.InvariantCultureIgnoreCase)
The method accepts an IEqualityComparer, the docs.
As pointed out by Steven Doggart, ListBox Items require the use of OfType(Of T):
lbxEmailAliases.Items.OfType(Of String).Contains(ItemtoAdd, StringComparer.InvariantCultureIgnoreCase)
An alternative could be the FindString-method:
If lbxEmailAliases.FindString(ItemtoAdd) = ListBox.NoMatches Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If
Note: This method searches for items that start with the specified string and returns the index of the first found item.
Means it will find jdoe#domain.com even if the existing e-mail-address is jdoe#domain.computer.com.
So maybe it's not the best solution for your specific case.
EDIT:
You can use FindStringExact instead. Like this you'll get the wanted case insensitive, non-partial comparison.
If lbxEmailAliases.FindStringExact(ItemtoAdd) = ListBox.NoMatches Then
lbxEmailAliases.Items.Add(ItemtoAdd)
End If

Reading from a string using sscanf in Matlab

I'm trying to read a string in a specific format
RealSociedad
this is one example of string and what I want to extract is the name of the team.
I've tried something like this,
houseteam = sscanf(str, '%s');
but it does not work, why?
You can use regexprep like you did in your post above to do this for you. Even though your post says to use sscanf and from the comments in your post, you'd like to see this done using regexprep. You would have to do this using two nested regexprep calls, and you can retrieve the team name (i.e. RealSociedad) like so, given that str is in the format that you have provided:
str = 'RealSociedad';
houseteam = regexprep(regexprep(str, '^<a(.*)">', ''), '</a>$', '')
This looks very intimidating, but let's break this up. First, look at this statement:
regexprep(str, '^<a(.*)">', '')
How regexprep works is you specify the string you want to analyze, the pattern you are searching for, then what you want to replace this pattern with. The pattern we are looking for is:
^<a(.*)">
This says you are looking for patterns where the beginning of the string starts with a a<. After this, the (.*)"> is performing a greedy evaluation. This is saying that we want to find the longest sequence of characters until we reach the characters of ">. As such, what the regular expression will match is the following string:
<ahref="/teams/spain/real-sociedad-de-futbol/2028/">
We then replace this with a blank string. As such, the output of the first regexprep call will be this:
RealSociedad</a>
We want to get rid of the </a> string, and so we would make another regexprep call where we look for the </a> at the end of the string, then replace this with the blank string yet again. The pattern you are looking for is thus:
</a>$
The dollar sign ($) symbolizes that this pattern should appear at the end of the string. If we find such a pattern, we will replace it with the blank string. Therefore, what we get in the end is:
RealSociedad
Found a solution. So, %s stops when it finds a space.
str = regexprep(str, '<', ' <');
str = regexprep(str, '>', '> ');
houseteam = sscanf(str, '%*s %s %*s');
This will create a space between my desired string.

C# 4.0 function to check for first four characters in the string

I need to validate for valid code name.
So, my string can have values like below:
String test = "C000. ", "C010. ", "C020. ", "C030. ", "CA00. ","C0B0. ","C00C. "
So my function needs to validate below conditions:
It should start with C
After that next 3 characters should be numeric before .
Rest it can be anything.
So in above string values, only ["C000.", "C010.", "C020.", "C030."] are valid ones.
EDIT:
Below is the code I tried:
if (nameObject.Title.StartsWith(String.Format("^[C][0-9]{3}$",nameObject.Title)))
I'd suggest a regex, for example (written off the top of my head, may need work):
string s = "C030.";
Regex reg = new Regex("C[0-9]{3,3}\\.");
bool isMatch = reg.IsMatch(s);
This regex should do the trick:
Regex.IsMatch(input, #"C[0-9]{3}\..*")
Check out http://www.techotopia.com/index.php/Working_with_Strings_in_C_Sharp
for a quick tutorial on (among other things) individual access of string elements, so you can test each element for your criteria.
If you think your criteria may change, using regular expressions gives you maximum flexibility (but is more runtime intensive than regular string-element evaluation). In your case, it may be overkill, IMHO.

Resources