Reputation: 748
I have some comma separated numbers in a string out of which I want to match a specific number. For the example string "18, 34, 22, 9, 2, 56" I want to match the number "2" but not the two "2s" in 22. How can I obtain that?
Upvotes: 2
Views: 113
Reputation: 4384
you can use grep
echo "18, 34, 22, 9, 2, 56" | grep -E -o "^2,| 2,| 2$"
and substitute '2' in grep regex by any number you search in your comma separated numbers string
Upvotes: 0
Reputation: 2042
You can solve that without a regular expression using ordinary string functions which are provided by most of the prog languages. For example one solution in Python. Add a comma at the start and the end:
s=", 18, 34, 22, 9, 2, 56,"
s.find(', 2,')
In case the search string can't be found the function returns -1. In case you insist on a regexp the pattern could look the same.
Upvotes: 1
Reputation:
This maybe not the best method but you can try something like this
string NUmbers= "18,22,34,52";
string[] NewNos=NUmbers.Split(',');
for(int i=0;i<NewNos.Length;i++)
{
if(NewNos[i].ToString().Contains("2"))
{
//do whatever you want
}
}
Upvotes: 0
Reputation: 13450
use this regular expression \b2\b
replace 2
with your value
Upvotes: 1