Regex match everything not between a pair of characters - regex

Suppose a string (representing elapsed time in the format HH:MM:ss) like this:
"123:59:00"
I want to match everything except the numbers for the minutes, i.e.: the regex should match the bold parts and not the number between colons:
"123: 59 :00"
In the example, the 59 should be the only part unmatched.
Is there any way to accomplish this with a js regex?
EDIT: I'm asking explicitly for a regex, because I'm using the Notion Formula API and can only use JS regex here.

You don't necessarily need to use RegEx for this. Use split() instead.
const timeString = "12:59:00";
const [hours, _, seconds] = timeString.split(":");
console.log(hours, seconds);
If you want to use Regex you can use the following:
const timeString = "12:59:00";
const matches = timeString.match(/(?<hours>^\d{2}(?=:\d{2}:))|(?<seconds>(?<=:\d{2}:)\d{2}$)/g);
console.log(matches);
// if you want to include the colons use this
const matchesWithColons = timeString.match(/(?<hours>^\d{2}:(?=\d{2}:))|(?<seconds>(?<=:\d{2}):\d{2}$)/g);
console.log(matchesWithColons);
You can drop the named groups ?<hours> and ?<seconds>.

Using split() might be the most canonical way to go, but here is a regex approach using match():
var input = "123:59:00";
var parts = input.match(/^[^:]+|[^:]+$/g);
console.log(parts);
If you want to also capture the trailing/leading colons, then use this version:
var input = "123:59:00";
var parts = input.match(/^[^:]+:|:[^:]+$/g);
console.log(parts);

Could also work
^([0-9]{2})\:[0-9]{2}\:([0-9]{2})$/mg

Related

Parsing a string by using regex

I need to parse an input string that has the format of
AB~11111, AB~22222, AB~33333, AB~44444
into separate strings:
AB~11111, AB~22222, AB~33333, and AB~44444
Here is my attempted Regex:
range = "([^~,\n]+~[^,]+,)?";
non_delimiter = "[^,\n;]+";
range_regex = new RegExp(this.range + this.non_delimiter, 'g');
But somehow this regex would only parse the input string into
AB~11111, AB~22222 and AB~33333, AB~44444
instead of parsing the input string into individual strings.
Maybe this is missing the boat, but from your input what about something like:
AB~\d+
This should match each of the strings from the above: https://regex101.com/r/vVFDIG/1. And if there's variation (i.e., it can be other letters) then maybe something like:
[A-Z]{2}~\d+
Or whatever it would need to be but using the negative character class seems like quite a roundabout way of doing it. If that's the case, you could just do:
[^ ,]+
You should use a regex split here on ,\s*:
var input = "AB~11111, AB~22222, AB~33333, AB~44444";
var parts = input.split(/,\s*/);
console.log(parts);
If you need to check that the input also consists of CSV list of AB~11111 terms, then you may use test to assert that:
var input = "AB~11111, AB~22222, AB~33333, AB~44444";
console.log(/^[A-Z]{2}~\d{5}(?:,\s*[A-Z]{2}~\d{5})*$/.test(input));

How to use Regex expression to modify my variable value?

I have a variable rawvalue:
let rawvalue = {abc-def-qwe}
I want to use regex to remove the { and }; I can simply do this by truncating the first and last characters. I built the regex:
^.(.*.).$
I want to know how to apply this regex on my variable to get the desired output?
The syntax you're looking for is like this:
let input = "{abc-def-qwe}";
let re = /^.(.*.).$/;
let fixed = re.exec(input)[1]; // Get the first match group "abc-def-qwe"
Maybe, this RegEx might be a better choice, which creates one group and you can simply call it using $1 and replace your string:
^\{(.+)\}$
For implementation, you might use, maybe these posts: 1, 2, 3.

Match return substring between two substrings using regexp

I have a list of records that are character vectors. Here's an example:
'1mil_0,1_1_1_lb200_ks_drivers_sorted.csv'
'1mil_0_1_lb100_ks_drivers_sorted.csv'
'1mil_1_1_lb2_100_100_ks_drivers_sorted.csv'
'1mil_1_1_lb100_ks_drivers_sorted.csv'
From these names I would like to extract whatever's between the two substrings 1mil_ and _ks_drivers_sorted.csv.
So in this case the output would be:
0,1_1_1_lb200
0_1_lb100
1_1_lb2_100_100
1_1_lb100
I'm using MATLAB so I thought to use regexp to do this, but I can't understand what kind of regular expression would be correct.
Or are there some other ways to do this without using regexp?
Let the data be:
x = {'1mil_0,1_1_1_lb200_ks_drivers_sorted.csv'
'1mil_0_1_lb100_ks_drivers_sorted.csv'
'1mil_1_1_lb2_100_100_ks_drivers_sorted.csv'
'1mil_1_1_lb100_ks_drivers_sorted.csv'};
You can use lookbehind and lookahead to find the two limiting substrings, and match everything in between:
result = cellfun(#(c) regexp(c, '(?<=1mil_).*(?=_ks_drivers_sorted\.csv)', 'match'), x);
Or, since the regular expression only produces one match, the following simpler alternative can be used (thanks #excaza for noticing):
result = regexp(x, '(?<=1mil_).*(?=_ks_drivers_sorted\.csv)', 'match', 'once');
In your example, either of the above gives
result =
4×1 cell array
'0,1_1_1_lb200'
'0_1_lb100'
'1_1_lb2_100_100'
'1_1_lb100'
For me the easy way to do this is just use espace or nothing to replace what you don't need in your string, and the rest is what you need.
If is a list, you can use a loop to do this.
Exemple to replace "1mil_" with "" and "_ks_drivers_sorted.csv" with ""
newChr = strrep(chr,'1mil_','')
newChr = strrep(chr,'_ks_drivers_sorted.csv','')

add datetime as string to a string after matching a pattern in vb.net

I have this string for example: "Example_string.xml"
and i would like to add before the "." _DateTime of now so it will be like:
"Example_string_20151808185631.xml"
How can i achieve it? regex?
Yes, you can achieve that through the use of a look ahead. For instance:
Dim result As String = Regex.Replace("Example_string.xml", "(?=\.)", "_20151808185631")
Since the pattern only matches a position in the string (the position just before the period), rather than matching a portion of the text, the replace method doesn't actually replace any of the input text. It effectively just inserts the replacement text into that position in the string.
Alternatively, if you find that confusing, you could just match the period and then just include the period in the replacement text:
Dim result As String = Regex.Replace("Example_string.xml", "\.", "_20151808185631.")
If you don't want to just look for any period, and you want to be more safe about it (such as handling file names that contain multiple periods, then instead of \., you could use something like \.\w+$. However, if you need to make it that resilient, and it doesn't have to be done with RegEx, it would be better to use the Path.GetFileNameWithoutExtension and Path.GetExtension methods, as recommended by Crowcoder. For instance, you may also need to make it handle file names that have no extension, which even further complicates it.
or...
Path.GetFileNameWithoutExtension("Example_string.xml") + "_20151808185631" + Path.GetExtension("Example_string.xml")
How about:
Dim sFile As String = "Example_string.xml"
Dim sResult As String = sFile.ToLower.Replace(".xml", "_" & Format(Now(), "yyyyMMddHHmmss") & ".xml")
MsgBox(sresult, , sFile)

Regexp to match only n occurrences of a char in a string

I have a string like 2005:10:29 12:23:53 and I wish to replace only first two occurrences of : with -
Expected result 2005-10-29 12:23:53
EDIT:
I need this regexp in KDE's krename tool, where I can't edit/format the original [exifExif.Image.DateTime] witch returns the unwanted 2005:10:29 12:23:53 format, but there is a Find and Replace to post process the String
(?<=\d{4}):|:(?=\d{2}\s) does the job on rubular, but does not in KDE :(
I am sure there are more solutions.
EDIT:
:(?=\d{2}:\d{2}\s)|:(?=\d{2}\s) works even on KDE
I find this solution after I read
You can use a full-fledged regular expression inside the lookahead.
Most regular expression engines only allow literal characters and
alternation inside lookbehind, since they cannot apply regular
expression backwards.
in Regex tutorial
In Ruby, as scibuff suggests, you're probably better not using Regexps.
require 'date'
date = DateTime.parse("2005:10:29 12:23:53", "%Y:%m:%d %H:%M:%S")
date.strftime("%Y-%m-%d %H:%M:%S")
JavaScript:
Version 1
str = str.split(' ')[0].replace(/\:/g,'-')+' '+str.split(' ')[1]
Version 2
str = str.replace(/(\d{4}):(\d{2}):(\d{2})(.*)/,"$1-$2-$3 $4")
DEMO
Once again using regular expressions for something that can be achieved in a simpler, more elegant and more efficient way
var date = new Date('2005:10:29 12:23:53');
then format date accordingly, e.g.
function formatDate( date ){
return date.getFullYear() + '-' + ( get.getMonth() + 1 ) + '-' + ... ;
}
Simply call replace() twice:
"2005:10:29 12:23:53".replace(/:/,'-').replace(/:/,'-')