logo
down
shadow

Regex if condition c#


Regex if condition c#

By : Karim omar
Date : October 18 2020, 01:08 AM
Hope this helps Note that a regex approach does not sound quite good for a task like this. It can be used for small input strings, for larger ones, it is recommended that you write some more logic and parse text line by line.
So, more from academic interest, here is a regex solution showing how to replace with different replacement patterns based on whether the line matched is first or not:
code :
var pat = @"(?m)(?:(\A)|^(?!\A))(.*\b\s+(\d+)\r?\n)";
var s = "10 25\n32 44\n56 88\n102 127\n135 14510 25\n32 44\n56 88\n102 127\n135 145";
var res = Regex.Replace(s, pat, m => m.Groups[1].Success ? 
        $"0 {m.Groups[2].Value}{m.Groups[3].Value} " : $"{m.Groups[2].Value}{m.Groups[3].Value} ");
0 10 25
25 32 44
44 56 88
88 102 127
127 135 14510 25
25 32 44
44 56 88
88 102 127
127 135 145


Share : facebook icon twitter icon
javascript regex replace, how to provide regex condition (and flags) as variable instead of inline?

javascript regex replace, how to provide regex condition (and flags) as variable instead of inline?


By : Chirag
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Using the JS replace function with regex, and will have dozens of replace statements. , I would use a lookup object to map the originals to URLs:
code :
// Original string
var o = "MySql is a DBMS, whereas javascript is a client side scripting language";

//Patterns
var patterns = {
    "javascript": "http://js.com/",
    "mysql": "http://www.mysql.com/"
};

//Constructing regex
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
var keys = [];
for (i in patterns) {
    if (patterns.hasOwnProperty(i)) {
        keys.push(RegExp.escape(i));
    }
}
var pattern = new RegExp("\\b(" + keys.join("|") + ")\\b", "gi");

//Replace
var n = o.replace(pattern, function(m, g1) {
    return "<a href='" + patterns[g1.toLowerCase()] + "'>" + g1 + "< /a>";
});
console.log(n);
// Original string
var o = '<p>Test 1 (JavaScript - <strong>1st keyword instance to be replaced</strong>): <br><a href="http://js1.net">Link to JavaScript site (existing URL)</a> is a scripting language commonly implemented as part of a web browser in order to create enhanced user interfaces and dynamic websites. JavaScript is very flexible.</p><p>more text here... and another mention of JavaScript. also javascript and JAVAScrIPT <br><br></p><p>Test 2 (MySQL - <strong>1st keyword instance to be replaced</strong>): <br><a href="http://www.mysql.com">MySQL</a>  (existing URL) is the most popular open-source database system.</p> <p><a href="http://www.themysqllink.com">link to a MySQL site</a> (existing URL).</p><p> More stuff about Mysql, also mysql and mySQL</p>';

//Patterns
var patterns = {
    "javascript": "http://js.com/",
    "mysql": "http://www.mysql.com/",
    "mention": "http://www.x.com/"
};

//Number of replacements
var num = 1;

//Constructing regex
RegExp.escape = function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
var keys = [];
for (key in patterns) {
    if (patterns.hasOwnProperty(key)) {
        keys.push(RegExp.escape(key));
    }
}
var regexen = [];
for (var i = 0; i < keys.length; i++) {
    regexen[i] = new RegExp("\\b(" + keys[i] + ")\\b(?![^<]*?<\/a>)", "i");
}

//Replace
for (var i = 0; i < regexen.length; i++) {
    var count = 0;
    var pattern = regexen[i];
    while (count < num) {
        o = o.replace(pattern, function(m, g1) {
            return "<a href='" + patterns[g1.toLowerCase()] + "'>" + g1 + "</a>";
        });
        count++;
    }
}
document.write(o);
Regex: Match a condition, then find the first occurrence of another condition that precedes it on the same line. Possibl

Regex: Match a condition, then find the first occurrence of another condition that precedes it on the same line. Possibl


By : Apoorva Bhargav
Date : March 29 2020, 07:55 AM
Does that help Using Regular Expressions, I am looking to find a piece of text based on condition A, then look backwards from the found point and match condition B and replace the text of condition A with B's text. , Find using this:
code :
(<h2>)(.*)(</h2>.*)(REPLACE THIS TEXT)
$1$2$3$2
RegEX match if condition 1 exists but condition 2 does not RegEX

RegEX match if condition 1 exists but condition 2 does not RegEX


By : nmabachi
Date : March 29 2020, 07:55 AM
it helps some times I pushed the sent to after dob etc. so that sent and date will be ignored when they come together.
code :
(?i)\b(dob|date of birth|birth\s?date|birthday|born|d.o.b)\b(?:(?!Sent:)\D){0,500}\b(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\b\D{0,5}\b(\d{1,2})\D{0,20}(\d{2,4})\b
Update pandas value when regex condition is satisfied with regex replace

Update pandas value when regex condition is satisfied with regex replace


By : user3311752
Date : March 29 2020, 07:55 AM
With these it helps Giving a DataFrame like this one, composed by more than 10k records:
code :
df = pd.DataFrame({"A":['CCANNNNNNTGG']})

df
        A
0   CCANNNNNNTGG

import re
def my_func(x):
    return re.sub(r'N', [A|C|G|T], x)

df['A'] = df.A.apply(my_func)

df
0    CCA[A|C|G|T][A|C|G|T][A|C|G|T][A|C|G|T][A|C|G|T][A|C|G|T]TGG
Name: A, dtype: object
Regex pattern force match with condition and not for another condition

Regex pattern force match with condition and not for another condition


By : user3589056
Date : March 29 2020, 07:55 AM
it helps some times I am trying to force to match with these conditions: , The regex you want to use is:
code :
\d{1,3} [A-Z]$
\b\d{1,3} [A-Z]$
Related Posts Related Posts :
  • How to join tables using LINQ and navigation properties
  • Deserialize Bytes Array directly to Object in JSON.Net
  • FileNotFoundException, but catch block is not entered (Async method)
  • How does GameRanger works?
  • See the AvailableFreeSpace of drives via IP-Address
  • How to convert Sql Datetime query into Linq
  • Email sending always fails, what is wrong with my contact us code
  • how to get a part from a string with regular expression in C#
  • Mapping List`1 to Object properties
  • Handle UnauthorizedAccessException When Directory.CreateDirectory() Run
  • Whats the equivalent of C# "Click.add" for Visual Basic .net
  • C# - Need help generating a random number and using the same number multiple times in other functions
  • WPF Binding StringFormat doesn't change the output
  • Convert Expression<Func<TDocument, object>> to Expression<Func<TDocument, TOutput>>
  • How do I save current user in another table when saving objects?
  • CLOCKS_PER_SEC equivalent in C#
  • Unable to start debugging on the web server. Operation not supported. Unknown error 0x800040005
  • Why is private variable of another class accessible inside .Equals override?
  • Why does HttpClient continue to fail during subsequent retries using Polly?
  • How to create autocompletion in Excel?
  • image problems with webcamtexture
  • Most efficient way to search enumerable
  • How to pass array property in model Asp.net Core in HttpGet?
  • Installing a .NetStandard 2.0 Nuget package into a VS2015 Net 4.6.1 project
  • How to sum a field on linq that has a where clause which pulls data that returns nulls too?
  • Can we assign more RAM to a program that gets an OutOfMemoryException
  • GC Alloc for unknown reason
  • How to address "You are using an unsupported command-line flag: --ignore-certificate-errors, Stability and security
  • get image url from SharePoint genericlist with CSOM
  • Calculate difference between datetime and convert to int
  • The type or namespace name `IGraphResult` could not be found. But it's there and it works fine elsewhere
  • Using MEF in an Azure function App
  • How to listen for Pub/Sub messages in an ASP.NET Core app continuously?
  • How to store multiple checked Checkbox values in DB using ASP.NET MVC
  • What causes this amazon build error in UWP Release mode?
  • Callback function end after creating instance of class (c#)
  • Is there a way to perform a chained null check in a dynamic/expando?
  • SimpleInjector lazy generic registration
  • SD card directory
  • System.Net.Http in net47
  • C++ how to implement an array of list
  • Xamarin Forms Displaying the list of email recipients
  • run and handle output from ps1 script
  • How to set change log entries user in Dynamics Nav 2016
  • Is it possible to query all companies via ODATA in Dynamics Nav 2016
  • Reading Json Content and Displaying it
  • Is BouncyCastle's SecureRandom in C# threadsafe?
  • The argument 'name' cannot be null, empty or contain only white space
  • Reinstall NuGet packages for ASP.NET Website outside Visual Studio
  • How to Setup Mock<UserManager<TUser >>
  • How to add a property that will be passed through more than one class
  • Programmatically check authenticoded files in NuGet Package
  • Using properties depending of the content of a class
  • MSTest Unit Test Adapter Failing to Connect to Data Source When Tests From New Test Project Are Introduced to Solution
  • AForge download comes with no .dll files, how to use it?
  • LINQ to DataSet multi-table left join
  • after migrate to .net core 2.0 session stop working correctly
  • How to make sure a user completes their profile in aspnet core 2.0?
  • Is rapidly creating BouncyCastle SecureRandom instances problematic?
  • Cannot display Fetched JSON data from Web API call since backslashes are in response
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com