Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sub-strings from a string that are enclosed using some specified character

Suppose I have a string

Likes (20)

I want to fetch the sub-string enclosed in round brackets (in above case its 20) from this string. This sub-string can change dynamically at runtime. It might be any other number from 0 to infinity. To achieve this my idea is to use a for loop that traverses the whole string and then when a ( is present, it starts adding the characters to another character array and when ) is encountered, it stops adding the characters and returns the array. But I think this might have poor performance. I know very little about regular expressions, so is there a regular expression solution available or any function that can do that in an efficient way?

like image 252
Aishwarya Shiva Avatar asked Sep 05 '13 08:09

Aishwarya Shiva


People also ask

How do you take a specific part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do I split a string into substring?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do you grab part of a string in Python?

Extract a substring by slicing You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end.

How do you extract a substring from a string in Python regex?

We will use a regular expression in Python to extract the substring in this example. We will utilize Python's built-in package re for regular expressions. The search() function in the preceding code looks for the first instance of the pattern supplied as an argument in the passed text.


2 Answers

If you don't fancy using regex you could use Split:

string foo = "Likes (20)";
string[] arr = foo.Split(new char[]{ '(', ')' }, StringSplitOptions.None);
string count = arr[1];

Count = 20

This will work fine regardless of the number in the brackets ()

e.g:

Likes (242535345)

Will give:

242535345

like image 110
DGibbs Avatar answered Nov 15 '22 02:11

DGibbs


Works also with pure string methods:

string result = "Likes (20)";
int index = result.IndexOf('(');
if (index >= 0)
{
    result = result.Substring(index + 1); // take part behind (
    index = result.IndexOf(')');
    if (index >= 0)
        result = result.Remove(index);    // remove part from )
}

Demo

like image 35
Tim Schmelter Avatar answered Nov 15 '22 02:11

Tim Schmelter