This is probably a really basic question, but I can't find any answers. I need to match a string by either two or more spaces OR an equals sign.
When I split this string: 9 x 13 = (8.9 x 13.4) (89 x 134)
with ( +) I get:
part 0: 9 x 13 = (8.9 x 13.4)
part 1: (89 x 134)
When I split it with (=) I get:
part 0: 9 x 13
part 1: (8.9 x 13.4) (89 x 134)
How can split by BOTH? Something like: (=)OR( +)
Edit:
This does not work(=)|( +), I was expecting:
part 0: 9 x 13
part 1: (8.9 x 13.4)
part 2: (89 x 134)
Your regex should have worked, except it would leave the spaces that were before and after the =. That's assuming you really did use two spaces in the ( +) part (which got normalized to one space by SO's formatting). This one yields the exact result you said you want:
#" {2,}|\s*=\s*"
Simply,
Pattern = "\s*=\s*|(?!\))\s+?(?=\()"
(=)|( +)
Is that good for you?
Explanation and example:
http://msdn.microsoft.com/en-us/library/ze12yx1d.aspx , scroll down to the 3rd remark...
You can use a regex like this: [= ]+
var regex = new Regex("[= ]+");
var parts = regex.Split("this is=a test");
// parts = [ "this", "is", "a", "test" ]
If you want to keep the separators enclose the regex in parens: ([= ]+)
Related
I'm trying to do regex pattern which will match to this:
Name[0]/Something
or
Name/Something
Verbs Name and Something will be always known.
I did for Name[0]/Something, but I want make pattern for this verb in one regex
I've tried to sign [0] as optional but it didn't work :
var regexPattern = "Name" + #"\([\d*\]?)/" + "Something"
Do you know some generator where I will input some verbs and it will make pattern for me?
Use this:
Name(\[\d+\])?\/Something
\d+ allows one or more digits
\[\d+\] allows one or more digits inside [ and ]. So it will allow [0], [12] etc but reject []
(\[\d+\])? allows digit with brackets to be present either zero times or once
\/ indicates a slash (only one)
Name and Something are string literals
Regex 101 Demo
You were close, the regex Name(\[\d+\])?\/Something will do.
The problem is with first '\' in your pattern before '('.
Here is what you need:
var str = "Name[0]/Something or Name/Something";
Regex rg = new Regex(#"Name(\[\d+\])?/Something");
var matches = rg.Matches(str);
foreach(Match a in matches)
{
Console.WriteLine(a.Value);
}
var string = 'Name[0]/Something';
var regex = /^(Name)(\[\d*\])?\/Something$/;
console.log(regex.test(string));
string = 'Name/Something';
console.log(regex.test(string));
You've tried wrong with this pattern: \([\d*\]?)/
No need to use \ before ( (in this case)
? after ] mean: character ] zero or one time
So, if you want the pattern [...] displays zero or one time, you can try: (\[\d*\])?
Hope this helps!
i think this is what you are looking for:
Name(\[\d+\])?\/Something
Name litteral
([\d+])? a number (1 or more digits) between brackets optional 1 or 0 times
/Something Something litteral
https://regex101.com/r/G8tIHC/1
I'm pretty bad at Regex (C#) with my attempts at doing the following giving non-sense results.
Given string: 058:09:07
where only the last two digits are guaranteed, I need the result of:
"58y 9m 7d"
The needed rules are:
The last two digits "07" are days group and always present. If "00", then only the last "0" is to be printed,
The group immediately to the left of "07" which ends with ":" signify the months and are only present if enough days are present to lead into months. Again, if "00", then only the last "0" is to be printed,
The group immediately to the left of "09:" which ends with ":" signify years and will only be present if more then 12 months are needed.
In each group a leading "0" will be dropped.
(This is the result of an age calculation where 058:09:07 means 58 years, 9 months, and 7 days old. The ":" (colon) always used to separate years from months from days).
Example:
058:09:07 --> 58y 9m 7d
01:00 --> 1m 0d
08:00:00 --> 8y 0m 0d
00 --> 0d
Any help is most appreciated.
Well, you can pretty much do this without regex.
var str = "058:09:07";
var integers = str.Split(':').Select(int.Parse).ToArray();
var result = "";
switch(integers.Length)
{
case 1:
result = string.Format("{0}d", integers[0]); break;
case 2:
result = string.Format("{0}m {1}d", integers[0], integers[1]); break;
case 3:
result = string.Format("{0}y {1}m {2}d", integers[0], integers[1], integers[2]); break;
}
If you want to use regex so bad, that it starts to hurt, you can use this one instead:
var integers = Regex.Matches(str, "\d+").Cast<Match>().Select(x=> int.Parse(x.Value)).ToArray();
But, its overhead, of course. You see, regex is not parsing language, its pattern matching language, and should be used as one. For example, for finding substrings in strings. If you can find final substrings simply by cutting it by char, why not to use it?
DISCLAIMER: I am posting this answer for the educational purposes. The easiest and most correct way in case the whole string represents the time span eocron06's answer is to be used.
The point here is that you have optional parts that go in a specific order. To match them all correctly you may use the following regex:
\b(?:(?:0*(?<h>\d+):)?0*(?<m>\d+):)?0*(?<d>\d+)\b
See the regex demo
Details:
\b - initial word boundary
(?: - start of a non-capturing optional group (see the ? at the end below)
(?:0*(?<h>\d+):)? - a nested non-capturing optional group that matches zero or more zeros (to trim this part from the start from zeros), then captures 1+ digits into Group "h" and matches a :
0*(?<m>\d+): - again, matches zero or more 0s, then captures one or more digits into Group "m"
)? - end of the first optional group
0*(?<d>\d+) - same as the first two above, but captures 1+ digits (days) into Group "d"
\b - trailing word boundary
See the C# demo where the final string is built upon analyzing which group is matched:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var pattern = #"\b(?:(?:0*(?<h>\d+):)?0*(?<m>\d+):)?0*(?<d>\d+)\b";
var strs = new List<string>() {"07", "09:07", "058:09:07" };
foreach (var s in strs)
{
var result = Regex.Replace(s, pattern, m =>
m.Groups["h"].Success && m.Groups["m"].Success ?
string.Format("{0}h {1}m {2}d", m.Groups["h"].Value, m.Groups["m"].Value, m.Groups["d"].Value) :
m.Groups["m"].Success ?
string.Format("{0}m {1}d", m.Groups["m"].Value, m.Groups["d"].Value) :
string.Format("{0}d", m.Groups["d"].Value)
);
Console.WriteLine(result);
}
}
}
Ive seen a few answers that are similar but none seem to go far enough. I need to split the string when the letters change to numbers and back. The trick is the pattern is variable meaning there can be any number of letter or number groupings.
For Example
AB1000 => AB 1000
ABC1500 => ABC 1500
DE160V1 => DE 160 V 1
FGG217H5IJ1 => FGG 217 H 5 IJ 1
Etc.
If you want to split the string, one way would be lookarounds:
string[] results = Regex.Split("FGG217H5IJ1", #"(?<=\d)(?=\D)|(?<=\D)(?=\d)");
Console.WriteLine(String.Join(" ", results)); //=> "FGG 217 H 5 IJ 1"
You can use a regex like this:
[A-Z]+|\d+
Working demo
I'm trying to separate the tokens on a string expression. The expression looks like this:
-1-2+-3
This is the regex I'm using:
[\d\.]+|[-][\d\.]+|\+|\-|\*|\/|\^|\(|\)
This brings me these matches:
-1
-2
+
-3
I was expecting:
-1
-
2
+
-3
Any ideas how can I distinct negative numbers from operators?
Maybe you could try this one; it makes use of a look-behind:
((?<=\d)[+*\/^()-]|\-?[\d.]+)
I tested it here.
Basically, makes sure that there is a number before the operator to decide what to match. So, if there is a digit before the operator, treat the operator alone, otherwise, combine the minus with the digit.
EDIT: Separated the brackets from the lot, just in case (demo):
((?<=\d)[+*\/^-]|[()]|\-?[\d.]+)
This pattern should do what you're looking for:
^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$
For example:
var input = "-1-2+-3";
var pattern = #"^(?:(?<num>-?[\d\.]+)(?:(?<op>[-+*/^])|$))+$";
var match = Regex.Match(input, pattern);
var results =
from Group g in match.Groups.Cast<Group>().Skip(1)
from Capture c in g.Captures
orderby c.Index
select c.Value;
Will produce:
-1
-
2
+
-3
What is the regular expression for removing ONE space?
e.g:
H e l l o W o r l d ----> Hello World
(Notice that there's still one space in between Hello World. It has two space in between to begin with)
FYI, I'm working with C# regex:
Previously I did something like this, but it doesn't work properly for the above case:
Regex pattern = new Regex(#"[ ]{2,}");
pattern.Replace(content, #" ")
To remove one space from all groups of one or spaces, use
pattern = Regex.Replace(content, " ( *)", "$1");
To change n spaces to floor(n/2) spaces, use
pattern = Regex.Replace(content, " ( ?)", "$1");
I tried to add examples but stackoverflow consolidates whitespace even in inline code spans it seems.
Explanation, as requested: The first finds a space followed by zero or more spaces and replaces it with the zero or more spaces, reducing the length by 1. The second finds each group of one or two spaces and replaces it by zero or one spaces, changing 1 to 0 in one replacement, 2 to 1 in one replacement, 3 to 2 in two replacements, etc.
Try using a negative look ahead.
Regex pattern = new Regex(#"\s(?!\s)");
Console.WriteLine(pattern.Replace(content, ""))
If I understand you want to remove exactly one space for each occurrence of one or more consecutive spaces.
For that you need to create a regex which matches each such occurrence putting all but one of the spaces into a capturing group and then replace each occurrence with capturing group. So if there are 2 spaces next to each other, they're found as one match and the second space goes in the capturing group. So after the replacement two spaces have been reduced to one space.
Regex pattern = new Regex(#" ( *)");
String newString = pattern.Replace("H e l l o W o r l d", "$1");
// newString == "Hello World"
Another way would be to use a match evaluator to use a two character match:
string s = Regex.Replace("H e l l o W o r l d", #"\s\S", x => x.Value[1].ToString());
Matches a whitespace followed by a non-whitespace and removes those whitespaces.
Regex.Replace(input, #"(\s)(\S)", #"$2");
It kind of looks like it's a string with an added space after each character. If it's so then you could get the original string by retrieving only the even indexed characters in the string.
var input = "H e l l o W o r l d ";
var res = String.Join("", input.Where((c, i) => (i % 2) == 0));
By no means a general solution given the nature of your problem, but in this particular case it looks as though you could get away with removing spaces that touch a word character on either side: on the left, for example:
Regex.Replace(content, " \b", "");
The expression "[\s]{1}" should do it