When I get the list value from the "Author" column on a list in SharePoint 2010, the following gets displayed:
2;#SP10Setup
Now the user that created that particular list item was "SP10Setup", now is there a simple way to remove "2;#" at the beginning of SP10Setup without affecting the digits in "SP10Setup"?
I have a method that currently is stripping out all digits
//method to strip out unnecessary digits
public static string RemoveDigits(string key)
{
return Regex.Replace(key, #"\d", "");
}
this is how I get the particular list item value:
string author = listItem["Author"].ToString();
this is how I removed unwanted digits and characters:
//calling the RemoveCharacter method
string noDigitsAuthor = RemoveDigits(author);
string cleanedupAuthor = noDigitsAuthor.Replace(";", "").Replace("#", "");
The result I get from this is "SPSetup", but ideally I would want the result to be "SP10Setup".
What would be the quickest and easiest way to achieve this...
Thanks in Advance
You should not do it yourself.
Use SPFieldLookupValue class
String author = "2;#SP10Setup";
SPFieldLookupValue lookup = new SPFieldLookupValue(author);
string cleanedupAuthor = lookup.LookupValue;
int authorId = lookup.LookupId;
so you will have:
cleanedupAuthor = "SP10Setup"
authorId = 2
Use a regular expression like ^\d*;#. The ^ matches the start of the string, \d* says match zero or more digits and ;# are literals.
If your string is always the same length you could use http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.71%29.aspxenter link description here
first of al ';' and '#' are no digits. but you can take a loot at Removing text in string using Regex
Related
I have a string that I need to separate the product ID from, is this format
shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==
I need to get 556 out of there, and in the case of say 2658 etc also possible.
First index ":" I think
str.Substring(str.LastIndexOf(':') + 1);
But then I dont know how to just break after the match, regex better? any help apprecaited
EDIT
These do the exact same thing, seperating the first numbers out
LINQ:
var test = new string(str.Substring(str.IndexOfAny("0123456789".ToCharArray())).TakeWhile(char.IsDigit).ToArray());
Reggex:
var test = Regex.Match(str, #"\d+").Value;
So bears the question, which is better approach?
If the string format is fixed, use the Split function
string str = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
int id = Convert.ToInt32(str.Split(':')[2]);
Console.WriteLine(id);
I'd probably use Regex:
var id = Regex.Match(input, #"\?id:(?<x>\d+)").Groups["x"].Value
Decoded, that Regex means "literally match ?id: then start a capturing group called x and capture one or more digits into it"
The returned Match will have a Groups property that we index by x and retrieve the value
If you want it as an int you can int.Parse the result-you won't need a TryParse because the Regex will have only matched digits
If the format of the string is fixed then this would work:
input[9..input.IndexOf(':',10)];
And it would be more performant than Regex or Split
If you wanted a substring that works with a format change, perhaps:
var x = input.IndexOf("?id:") + 4;
var id = input[x..input.IndexOf(':',x+1)];
This will work even if the order of items changes.
string original = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
string startWithId = original.Substring(original.IndexOf("id:") + 3);
string onlyId = startWithId.Split(':')[0];
Console.WriteLine(onlyId);
I have a string which I extract from an HTML document like this:
var elas = htmlDoc.DocumentNode.SelectSingleNode("//a[#class='a-size-small a-link-normal a-text-normal']");
if (elas != null)
{
//
_extractedString = elas.Attributes["href"].Value;
}
The HREF attribute contains this part of the string:
gp/offer-listing/B002755TC0/
And I'm trying to extract the B002755TC0 value, but the problem here is that the string will vary by its length and I cannot simply use Substring method that C# offers to extract that value...
Instead I was thinking if there's a clever way to do this, to perhaps a match beginning of the string with what I search?
For example I know for a fact that each href has this structure like I've shown, So I would simply match these keywords:
offer-listing/
So I would find this keyword and start extracting the part of the string B002755TC0 until the next " / " sign ?
Can someone help me out with this ?
This is a perfect job for a regular expression :
string text = "gp/offer-listing/B002755TC0/";
Regex pattern = new Regex(#"offer-listing/(\w+)/");
Match match = pattern.Match(text);
string whatYouAreLookingFor = match.Groups[1].Value;
Explanation : we just match the exact pattern you need.
'offer-listing/'
followed by any combination of (at least one) 'word characters' (letters, digits, hyphen, etc...),
followed by a slash.
The parenthesis () mean 'capture this group' (so we can extract it later with match.Groups[1]).
EDIT: if you want to extract also from this : /dp/B01KRHBT9Q/
Then you could use this pattern :
Regex pattern = new Regex(#"/(\w+)/$");
which will match both this string and the previous. The $ stands for the end of the string, so this literally means :
capture the characters in between the last two slashes of the string
Though there is already an accepted answer, I thought of sharing another solution, without using Regex. Just find the position of your pattern in the input + it's lenght, so the wanted text will be the next character. to find the end, search for the first "/" after the begining of the wanted text:
string input = "gp/offer-listing/B002755TC0/";
string pat = "offer-listing/";
int begining = input.IndexOf(pat)+pat.Length;
int end = input.IndexOf("/",begining);
string result = input.Substring(begining,end-begining);
If your desired output is always the last piece, you could also use split and get the last non-empty piece:
string result2 = input.Split(new string[]{"/"},StringSplitOptions.RemoveEmptyEntries)
.ToList().Last();
I need to extract all words between { } brackets and place in a string array.
The problem is that the text between the brackets is dynamic.
For example:
Hi {name}, thanks for visiting {site}
In this text i want to get name and site words place in a array.
Thanks!
Solution : you can use Substring() function to retrieve the part of the string.
Syntax: Substring(int startindex,int length);
Steps:
1. you need to send the starting index(1) of { to Substring() function as first parameter.
2. you need to send the length of string to be retrieved that means index(2) of } in the form of length (index2-index1) to Substring() function as second parameter.
Try this:
String middlevalue="";
String str = "thanks for visiting {site}";
int index1= str.IndexOf("{");
index1++;
int index2=str.IndexOf("}");
if(index1!=-1 && index2!=-1)
middlevalue=str.Substring(index1, (index2 - index1)));
Output:
middlevalue contains -> site
Regex should work for you, note that all the words between {...} should not contain any {...}.
var items = Regex.Matches(input, "\{[^{]+\}").Cast<Match>()
.Select(m=>m.Value.Trim('{','}')).ToArray();
Adding to King's answer, this will help you retrieve just the keys without surrounding brackets.
Regex.Matches(input, #"\{(?<Value>[^{]+)\}").Cast<Match>()
.Select(m=>m.Groups["Value"].Value).ToArray();
Try this:
var regex = #"(?<=\{)[^}]*(?=\})";
var text = "Hello my name is {James}";
var matches = Regex.Matches(text, regex);
I am having trouble splitting a string. I want to split only the words between 2 different chars:
string text = "the dog :is very# cute";
How can I grab only the words, is very, between the : and # chars?
You can use String.Split() method with params char[];
Returns a string array that contains the substrings in this instance
that are delimited by elements of a specified Unicode character array.
string text = "the dog :is very# cute";
string str = text.Split(':', '#')[1]; // [1] means it selects second part of your what you split parts of your string. (Zero based)
Console.WriteLine(str);
Here is a DEMO.
You can use it any number of you want.
That's not really a split at all, so using Split would create a bunch of strings that you don't want to use. Simply get the index of the characters, and use SubString:
int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
use this code
var varable = text.Split(':', '#')[1];
Regex regex = new Regex(":(.+?)#");
Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value);
One of the overloads of string.Split takes a params char[] - you can use any number of characters to split on:
string isVery = text.Split(':', '#')[1];
Note that I am using that overload and am taking the second item from the returned array.
However, as #Guffa noted in his answer, what you are doing is not really a split, but extracting a specific sub string, so using his approach may be better.
Does this help:
[Test]
public void split()
{
string text = "the dog :is very# cute" ;
// how can i grab only the words:"is very" using the (: #) chars.
var actual = text.Split(new [] {':', '#'});
Assert.AreEqual("is very", actual[1]);
}
Use String.IndexOf and String.Substring
string text = "the dog :is very# cute" ;
int colon = text.IndexOf(':') + 1;
int hash = text.IndexOf('#', colon);
string result = text.Substring(colon , hash - colon);
I would just use string.Split twice. Get the string to the right of the first separator. Then, using the result, get the string to the left of second separator.
string text = "the dog :is very# cute";
string result = text.Split(":")[1] // is very# cute";
.Split("#")[0]; // is very
It avoids playing around with indexes and regex which makes it more readable IMO.
I have the following strings:
string a = "1. testdata";
string b = "12. testdata xxx";
What I would like is to be able to extract the number into one string and the characters following the number into another. I tried using .IndexOf(".") and then remove, trim and
substrings. If possible I would like to find something simpler as I have this to do in a
lot of parts of my code.
if the format is always the same you could do:
a.Split('.');
Proposed solutions so far are not correct.
First, after Split('.') or Split(".") you will have space in the beginning of second substring.
Second, if you have more than one dot - you'll have to do something yet after the split.
More robust solution is below:
string a = "11. Test string. With dots.";
var res = a.Split(new[] {". "}, 2, StringSplitOptions.None);
string number = res[0];
string val = res[1];
Argument 2 specifies maximum number of strings to return. Thus when you have several dots - it will make a split only at the first.
string[]list = a.Split(".");
string numbers = list[0];
string chars = list[1];