Make Regex stop looking at \n - c#

I have the following string:
"\t Product: ces DEVICE TYPE \nSometext" //between ":" and "ces" are 9 white spaces
I need to parse the part "DEVICE TYPE". I'm trying to do this with Regex. I use this expression, which works.
((?<=\bProduct:)(\W+\w+){3}\b)
this expression returns:
" ces DEVICE TYPE"
The problem is here: Some devices have a string like this:
"\t Product: ces DEVICETYPE \nSometext"
If I use the same expression to parse the device type I get this as result:
" ces DEVICETYPE \nSometext"
How do I get my regex to stop when a \n is found?

Perhaps this?
(?<=ces)[^\\n]+
If all you want is what's after ces and before \n that is..

In .NET you can use RegexOptions.Multiline. This changes the behaviour of ^ and $.
Rather than meaning the start and end of your string, they now mean start and end of any line within your string.
Regex r = new Regex(#"(?<=\bProduct:).+$", RegexOptions.Multiline);

You could use:
(?m)((?<=\bProduct:).+)
Explanation:
(?m)((?<=\bProduct:).+)
Match the remainder of the regex with the options: ^ and $ match at line breaks (m) «(?m)»
Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:).+)»
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)»
Assert position at a word boundary «\b»
Match the characters “Product:” literally «Product:»
Match any single character that is not a line break character «.+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
or
((?<=\bProduct:)[^\r\n]+)
Explanation
((?<=\bProduct:)[^\r\n]+)
Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:)[^\r\n]+)»
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)»
Assert position at a word boundary «\b»
Match the characters “Product:” literally «Product:»
Match a single character NOT present in the list below «[^\r\n]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A carriage return character «\r»
A line feed character «\n»

Related

Regular Expression that matches on values after a pipe in between brackets

I'm still learning a lot about regex, so please forgive any naivety.
I've been using this site to test:
http://www.systemtextregularexpressions.com/regex.match
Basically, I'm having issues writing a regular expression that will match on any value after a pipe in between brackets.
Given an example string of:
"<div> \n [dont1.dont2|match1|match2] |dont3 [dont4] dont5. \n </div>"
Expected output would be a collection:
match1,
match2
The closest I've been able to get so far is:
(?!\[.*(\|)\])(?:\|)([\w-_.,:']*)
Above gives me the values, including the pipes, and dont3.
I've also tried this guy:
\|(.*(?=\]))
but it outputs:
|match1|match2
Here's one way of doing it:
(?<=\[[^\]]*\|)[^\]|]*
Here's the meaning of the pattern:
(?<=\[[^\]]*\|) - Lookbehind expression to ensure that any match must be preceded by an open bracket, followed by any number of non-close-bracket characters, followed by a pipe character
(?<= ... ) - Declares a lookbehind expression. Something matching the lookbehind must immediately precede the text in order for it the match. However, the part matched by the lookbehind is not included in the resulting match.
\[ - Matches an open bracket character
[^\]]* - Matches any number of non-close-bracket characters
\| - Matches a pipe character
[^\]|]* - Matches any number of characters which are neither close brackets nor pipe characters.
The lookbehind is greedy, so it will allow for any number of pipes between the open bracket and the matching text.
try this:
\[.*?(?:\|(?<mydata>.*?))+\]
note: the online tool will only show you the last capture inside a quantifed () for a given match, but .NET will remember each capture of a group that matches multiple times
Try this:
^<div>\s*[^|]+|([^|]+)|([^|]+)

Formatting a Phone number [duplicate]

This question already has answers here:
Replace non-numeric with empty string
(9 answers)
Closed 8 years ago.
How can I format a phone number from (###)###-#### to ##########? Is there best way to do that? I can use String.Substring to get each block of numbers and then concatenate them. But, Is there any other sophisticated way of doing it?
How about a simple Regex replace?
string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");
This is essentially just a white list for numbers only. See this fiddle: http://dotnetfiddle.net/ssdWSd
Input: (123) 456-7890
Output: 1234567890
I'd do it using LINQ:
var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray());
While regex also works, this doesn't require any special set up.
A simple way would be:
myString = myString.Replace("(", "");
myString = myString.Replace(")", "");
myString = myString.Replace("-", "");
Replace each character with an empty string.
Try this:
resultString = Regex.Replace(subjectString, #"^\((\d+)\)(\d+)-(\d+)$", "$1$2$3");
REGEX EXPLANATION
^\((\d+)\)(\d+)-(\d+)$
Assert position at the beginning of the string «^»
Match the character “(” literally «\(»
Match the regex below and capture its match into backreference number 1 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “)” literally «\)»
Match the regex below and capture its match into backreference number 2 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “-” literally «-»
Match the regex below and capture its match into backreference number 3 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$»
$1$2$3
Insert the text that was last matched by capturing group number 1 «$1»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the text that was last matched by capturing group number 3 «$3»

.NET Regex: negate previous character for the first character in string

Consider following string
"Some" string with "quotes" and \"pre-slashed\" quotes
Using regex, I want to find all the double quotes with no slash before them. So I want the regex to find four matches for the example sentence
This....
[^\\]"
...would find only three of them. I suppose that's because of the regex's state machine which is first validating the command to negate the presence of the slash.
That means I need to write a regex with some kind of look-behind, but I don't know how to work with these lookaheads and lookbehinds...im not even sure that's what I'm looking for.
The following attempt returns 6, not 4 matches...
"(?<!\\)
"(?<!\\")
Is what you're looking for
If you want to match "Some" and "quotes", then
(?<!\\")(?!\\")"[a-zA-Z0-9]*"
will do
Explanation:
(?<!\\") - Negative lookbehind. Specifies a group that can not match before your main expression
(?!\\") - Negative lookahead. Specifies a group that can not match after your main expression
"[a-zA-Z0-9]*" - String to match between regular quotes
Which means - match anything that doesn't come with \" before and \" after, but is contained inside double quotes
You almost got it, move the quote after the lookbehind, like:
(?<!\\)"
Also be ware of cases like
"escaped" backslash \\"string\"
You can use an expression like this to handle those:
(?<!\\)(?:\\\\)*"
Try this
(?<!\\)(?<qs>"[^"]+")
Explanation
<!--
(?<!\\)(?<qs>"[^"]+")
Options: case insensitive
Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!\\)»
Match the character “\” literally «\\»
Match the regular expression below and capture its match into backreference with name “qs” «(?<qs>"[^"]+")»
Match the character “"” literally «"»
Match any character that is NOT a “"” «[^"]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “"” literally «"»
-->
code
try {
if (Regex.IsMatch(subjectString, #"(?<!\\)(?<qs>""[^""]+"")", RegexOptions.IgnoreCase)) {
// Successful match
} else {
// Match attempt failed
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}

Regular Expression for string

I have a string like
e.g AHDFFH XXXX
where 'AHDFFH' can be char string of any length.
AND 'XXXX' will be repeated no. of 'X' chars of any length which needs to be replaced by auto incremented database value in a table.
I need to find repeated 'X' chars from above string using regular expression.
Can anyone please help me to figure this out..??
Try this:
\b(\p{L})\1+\b
Explanation:
<!--
\b(\p{L})\1+\b
Options: case insensitive; ^ and $ match at line breaks
Assert position at a word boundary «\b»
Match the regular expression below and capture its match into backreference number 1 «(\p{L})»
A character with the Unicode property “letter” (any kind of letter from any language) «\p{L}»
Match the same text as most recently matched by capturing group number 1 «\1+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at a word boundary «\b»
-->
is your meaning some chars + (on or some)space + some numbers?
if so u can use this regexpression:
\w+\s+(\d+)
c# codes like this:
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"\w+\s+(\d+)");
System.Text.RegularExpressions.Match m = regex.Match("aaaa 3333");
if(m.Success) {
MessageBox.Show(m.Groups[1].Value);
}

C# regex to replace a delimiter by another one

I'm working on pl/sql code where i want to replace ';' which is commented with '~'.
e.g.
If i have a code as:
--comment 1 with;
select id from t_id;
--comment 2 with ;
select name from t_id;
/*comment 3
with ;*/
Then i want my result text as:
--comment 1 with~
select id from t_id;
--comment 2 with ~
select name from t_id;
/*comment 3
with ~*/
Can it be done using regex in C#?
Regular expression:
((?:--|/\*)[^~]*)~(\*/)?
C# code to use it:
string code = "all that text of yours";
Regex regex = new Regex(#"((?:--|/\*)[^~]*)~(\*/)?", RegexOptions.Multiline);
result = regex.Replace(code, "$1;$2");
Not tested with C#, but the regular expression and the replacement works in RegexBuddy with your text =)
Note: I am not a very brilliant regular expression writer, so it could probably have been written better. But it works. And handles both your cases with one-liner-comments starting with -- and also the multiline ones with /* */
Edit: Read your comment to the other answer, so removed the ^ anchor, so that it takes care of comments not starting on a new line as well.
Edit 2: Figured it could be simplified a bit. Also found it works fine without the ending $ anchor as well.
Explanation:
// ((?:--|/\*)[^~]*)~(\*/)?
//
// Options: ^ and $ match at line breaks
//
// Match the regular expression below and capture its match into backreference number 1 «((?:--|/\*)[^~]*)»
// Match the regular expression below «(?:--|/\*)»
// Match either the regular expression below (attempting the next alternative only if this one fails) «--»
// Match the characters “--” literally «--»
// Or match regular expression number 2 below (the entire group fails if this one fails to match) «/\*»
// Match the character “/” literally «/»
// Match the character “*” literally «\*»
// Match any character that is NOT a “~” «[^~]*»
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
// Match the character “~” literally «~»
// Match the regular expression below and capture its match into backreference number 2 «(\*/)?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match the character “*” literally «\*»
// Match the character “/” literally «/»
A regex is not really needed - you can iterate on lines, locate the lines starting with "--" and replace ";" with "~" on them.
String.StartsWith("--") - Determines whether the beginning of an instance of String matches a specified string.
String.Replace(";", "~") - Returns a new string in which all occurrences of a specified Unicode character or String in this instance are replaced with another specified Unicode character or String.

Categories