I have a c# string expression where i'd like to replace all instances of '=' with '=='
e.g
1 = 1
should be
1 == 1
However, I can't just do a replace('=','==') because '1 == 1' would become '1 ==== 1'
Is there a Regex or something I could use instead?
You can use a Regex which will match only a single equals sign and call Replace on that Regex.
new Regex("={1,}").Replace("=", "==")
Returns ==
new Regex("={1,}").Replace("==", "==")
Returns ==
Related
I have following value in the table.
aaaaaa 26G 2.0G 23G 8 tmp
tmpfs 506M 0 506M 0 /dev/shm
I need to store first value that is ('aaaaaa' and'tmpfs') and second value (26 and 506) in another table. I got first value by
CAST(substr(COL_1,1,InStr(COL_1,' ')-1) AS VARCHAR2(10)) col
How do I get the second value such as 26 and 506 using substring and instring.?
I would recommend regexp_substr():
select regexp_substr(col1, '[^ ]+ ', 1, 1) as first,
regexp_substr(col1, '[^ ]+ ', 1, 2) as second
This returns the value with a space at the end. I think the pattern works without the space, because regular expression matching is greedy in Oracle:
select regexp_substr(col1, '[^ ]+', 1, 1) as first,
regexp_substr(col1, '[^ ]+', 1, 2) as second
There is an optional argument to instr where you can specify the nth occurrence of a specific string being searched.
CAST(substr(COL_1,InStr(COL_1,' ',1,1)+1,InStr(COL_1,' ',1,2)-InStr(COL_1,' ',1,1)-1) AS VARCHAR2(10))
To only extract the number from this substring, use regexp_substr. This assumes letters always follow one or more numeric characters.
regexp_substr(CAST(substr(COL_1,InStr(COL_1,' ',1,1)+1,InStr(COL_1,' ',1,2)-InStr(COL_1,' ',1,1)-1) AS VARCHAR2(10)),'\d+')
I'm new to C# so expect some mistakes ahead. Any help / guidance would be greatly appreciated.
I want to limit the accepted inputs for a string to just:
a-z
A-Z
hyphen
Period
If the character is a letter, a hyphen, or period, it's to be accepted. Anything else will return an error.
The code I have so far is
string foo = "Hello!";
foreach (char c in foo)
{
/* Is there a similar way
To do this in C# as
I am basing the following
Off of my Python 3 knowledge
*/
if (c.IsLetter == true) // *Q: Can I cut out the == true part ?*
{
// Do what I want with letters
}
else if (c.IsDigit == true)
{
// Do what I want with numbers
}
else if (c.Isletter == "-") // Hyphen | If there's an 'or', include period as well
{
// Do what I want with symbols
}
}
I know that's a pretty poor set of code.
I had a thought whilst writing this:
Is it possible to create a list of the allowed characters and check the variable against that?
Something like:
foreach (char c in foo)
{
if (c != list)
{
// Unaccepted message here
}
else if (c == list)
{
// Accepted
}
}
Thanks in advance!
Easily accomplished with a Regex:
using System.Text.RegularExpressions;
var isOk = Regex.IsMatch(foo, #"^[A-Za-z0-9\-\.]+$");
Rundown:
match from the start
| set of possible matches
| |
|+-------------+
|| |any number of matches is ok
|| ||match until the end of the string
|| |||
vv vvv
^[A-Za-z0-9\-\.]+$
^ ^ ^ ^ ^
| | | | |
| | | | match dot
| | | match hyphen
| | match 0 to 9
| match a-z (lowercase)
match A-Z (uppercase)
You can do this in a single line with regular expressions:
Regex.IsMatch(myInput, #"^[a-zA-Z0-9\.\-]*$")
^ -> match start of input
[a-zA-Z0-9\.\-] -> match any of a-z , A-Z , 0-9, . or -
* -> 0 or more times (you may prefer + which is 1 or more times)
$ -> match the end of input
You can use Regex.IsMatch function and specify your regular expression.
Or define manually chars what you need. Something like this:
string foo = "Hello!";
char[] availableSymbols = {'-', ',', '!'};
char[] availableLetters = {'A', 'a', 'H'}; //etc.
char[] availableNumbers = {'1', '2', '3'}; //etc
foreach (char c in foo)
{
if (availableLetters.Contains(c))
{
// Do what I want with letters
}
else if (availableNumbers.Contains(c))
{
// Do what I want with numbers
}
else if (availableSymbols.Contains(c))
{
// Do what I want with symbols
}
}
Possible solution
You can use the CharUnicodeInfo.GetUnicodeCategory(char) method. It returns the UnicodeCategory of a character. The following unicode categories might be what you're look for:
UnicodeCategory.DecimalDigitNumber
UnicodeCategory.LowercaseLetter and UnicodeCategory.UppercaseLetter
An example:
string foo = "Hello!";
foreach (char c in foo)
{
UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(c);
if (cat == UnicodeCategory.LowercaseLetter || cat == UnicodeCategory.UppercaseLetter)
{
// Do what I want with letters
}
else if (cat == UnicodeCategory.DecimalDigitNumber)
{
// Do what I want with numbers
}
else if (c == '-' || c == '.')
{
// Do what I want with symbols
}
}
Answers to your other questions
Can I cut out the == true part?:
Yes, you can cut the == true part, it is not required in C#
If there's an 'or', include period as well.:
To create or expressions use the 'barbar' (||) operator as i've done in the above example.
Whenever you have some kind of collection of similar things, an array, a list, a string of characters, whatever, you'll see at the definition of the collection that it implements IEnumerable
public class String : ..., IEnumerable,
here T is a char. It means that you can ask the class: "give me your first T", "give me your next T", "give me your next T" and so on until there are no more elements.
This is the basis for all Linq. Ling has about 40 functions that act upon sequences. And if you need to do something with a sequence of the same kind of items, consider using LINQ.
The functions in LINQ can be found in class Enumerable. One of the function is Contains. You can use it to find out if a sequence contains a character.
char[] allowedChars = "abcdefgh....XYZ.-".ToCharArray();
Now you have a sequence of allowed characters. Suppose you have a character x and want to know if x is allowed:
char x = ...;
bool xIsAllowed = allowedChars.Contains(x);
Now Suppose you don't have one character x, but a complete string and you want only the characters in this string that are allowed:
string str = ...
var allowedInStr = str
.Where(characterInString => allowedChars.Contains(characterInString));
If you are going to do a lot with sequences of things, consider spending some time to familiarize yourself with LINQ:
Linq explained
You can use Regex.IsMatch with "^[a-zA-Z_.]*$" to check for valid characters.
string foo = "Hello!";
if (!Regex.IsMatch(foo, "^[a-zA-Z_\.]*$"))
{
throw new ArgumentException("Exception description here")
}
Other than that you can create a list of chars and use string.Contains method to check if it is ok.
string validChars = "abcABC./";
foreach (char c in foo)
{
if (!validChars.Contains(c))
{
// Throw exception
}
}
Also, you don't need to check for == true/false in if line. Both expressions are equal below
if (boolvariable) { /* do something */ }
if (boolvariable == true) { /* do something */ }
I have expression like this
R4013[i] == 3 and R4014[i] == 2 AND R40[i] == 1 and R403[i+1] == 5 and R404[i+1] == 2 AND R405[i+1] == 1 R231[2]
I want to grap all the variable here with regex so I get variable R4013[i],R4014[i],R40[i] and so on.
I have already have regex pattern like this but not work
[RMB].+\[.+\]
You could try the below,
#"[RMB][^\[]*\[[^\]]*\]"
DEMO
[RMB] Picks up a single character from the given list.
[^\[]* negated character class which matches any character but not [ symbol, zero or more times.
\[ Matches a literal [ symbol.
[^\]]* Matches any character but not of ], zero or more times.
\] Matches the literal ] symbol.
Code:
String input = #"R4013[i] == 3 and R4014[i] == 2 AND R40[i] == 1 and R403[i+1] == 5 and R404[i+1] == 2 AND R405[i+1] == 1 R231[2]";
Regex rgx = new Regex(#"[RMB][^\[]*\[[^\]]*\]");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);
IDEONE
R\d+\[[^\]]*\]
This simple regex should do it, see demo:
https://regex101.com/r/wU7sQ0/3
Or you can simply modify your own regex to make it non greedy. Your regex uses .+ which is greedy and so it was capturing all data up to last [] instead of each variable. .+ is greedy and will not stop at the first instance of [ which you want. So use .+? instead
[RMB].+?\[.+?\]
https://regex101.com/r/wU7sQ0/4
Your regex [RMB].+\[.+\] will capture up to last [] as you have .+ after [RMB]. See here
string strRegex = #"[RMB].+?\[.+?\]";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = #"R4013[i] == 3 and R4014[i] == 2 AND R40[i] == 1 and R403[i+1] == 5 and R404[i+1] == 2 AND R405[i+1] == 1 R231[2]";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
How to extract User-Name value from strings below with Regex:
Acc sfjlsf56 1 0 User-Name=User_1, Group-Name=DCN_VPN_Support,
must be User_1
Acc t3we89ab 1 0 User-Name=John,Group-Name=DCN_VPN_Support,
must be John
Acc y5g769bo 1 0 User-Name=,Group-Name=DCN_VPN_Support,
must be null
To extract the username, we look for the User-Name= token, then match all characters after it that aren't a , (which denotes the next element). We tag this matched group with the name "username" to retrieved it later:
User-Name=(?<username>[^,]*)
var match = Regex.Match(stringToMatch, "User-Name=(?<username>[^,]*)");
string username = match.Success ? match.Groups["username"].Value : null;
Note that this will match the empty user as "" (String.Empty) rather than null. If null is required, simply translate it afterwards.
I believe the User-Name=[a-z\d]*, you can use
I'm attempting to match a string that can contain any number of numeric characters or a decimal point using the following regex:
([0-9.])*
Here's some C# code to test the regex:
Regex regex = new Regex("([0-9.])*");
if (!regex.IsMatch("a"))
throw new Exception("No match.");
I expect the exception to be thrown here but it isn't - am I using the Regex incorrectly or is there an error in the pattern?
EDIT: I'd also like to match a blank string.
The * quantifier means "match 0 or more". In your case, "a" returns 0 matches, so the regex still succeeds. You probably wanted:
([0-9.]+)
The + quantifier means "match 1 or more, so it fails on non-numeric inputs and returns no matches. A quick spin the regex tester shows:
input result
----- ------
[empty] No matches
a No matches
. 1 match: "."
20.15 1 match: "20.15"
1 1 match: "1"
1.1.1 1 match: "1.1.1"
20. 1 match: "20."
Looks like we have some false positives, let's revise the regex as such:
^([0-9]+(?:\.[0-9]+)?)$
Now we get:
input result
----- ------
[empty] No matches
a No matches
. No matches
20.15 1 match: "20.15"
1 1 match: "1"
1.1.1 No matches: "1.1.1"
20. No matches
Coolness.
Regex.IsMatch("a", "([0-9.])*") // true
This is because the group can match ZERO or more times.
Regex.IsMatch("a", "([0-9.])+") // false
You should use + instead of *
Regex reg = new Regex("([0-9.])+");
This should work fine.
When you use * any string can match this pattern in your case.