Find and replace between second and third slash - regex

I have urls with following formats ...
/category1/1rwr23/item
/category2/3werwe4/item
/category3/123wewe23/item
/category4/132werw3/item
/category5/12werw33/item
I would replace the category numbers with {id} for further processing.
/category1/{id}/item
How do i replace category numbers with {id}. I have spend last 4 hours with out proper conclusion.

Assuming you'll be running regex in JavaScript, your regex will be.
/^(\/.*?\/)([^/]+)/gm
and replacement string should look like $1whatever
var str = "your url strings ..."
var replStr = 'replacement';
var re = /^(\/.*?\/)([^/]+)/gm;
var result = str.replace(re, '$1'+replStr);
console.log(result);
based on your input, it should print.
/category1/replacement/item
/category2/replacement/item
/category3/replacement/item
/category4/replacement/item
/category5/replacement/item
See DEMO

We devide it into 3 groups
1.part before replacement
2.replacement
3.part after replacement
yourString.replace(//([^/]*\/[^/]+\/)([^/]+)(\/[^/]+)/g,'$1' + replacement+ '$3');
Here is the demo: https://jsfiddle.net/9sL1qj87/

Related

Regex match everything not between a pair of characters

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

extract alpha numeric id

I am looking to use RE to extract an id and description from the input which is in following format:
TTTT.1.A8This is important
AA.1.2.2ANothing is sometimes important
AAC.1A.2Everything sometimes is not important
Expected result:
ID description
TTTT.1.A8 This is important
AA.1.2.2A Nothing is sometimes important
AAC.1A.2 Everything sometimes is not important
I tried to achieve it as below:
img1 = re.compile(r"\w+\.\d+")
for in in input:
if re.search(img1,i.text):
req_id = str.strip(re.search(img1,i.text).group(0))
req_text = str.strip(re.split(img1,i.text)[1])
control_ids[req_id] = req_text
Find an upper case letter followed by a lower case letter:
/([A-Z][a-z])/g
then replace it as a space and itself $1 for JavaScript \g<1> for Python.
JavaScript: Regex101
Python: Regex101
const str =`TTTT.1.A8This is important
AA.1.2.2ANothing is sometimes important
AAC.1A.2Everything sometimes is not important`;
const rgx = new RegExp(/([A-Z][a-z])/, 'g');
const output = str.replace(rgx, ` $1`);
console.log(output);

Get digits between slashes or on the end in URL

I need a reg expression (for groovy) to match 7 digits between 2 slashes (in a url) or on the end of the url. So fe:
https://stackoverflow.com/questions/6032324/problem-with-this-reg-expression
I need 6032324 but it should also match:
https://stackoverflow.com/questions/6032324
If it has 1 digit more/less, I should not match.
Maybe its an easy reg exp but Im not so familiar with this :)
Thanks for you help!
Since you are parsing a URL, it makes sense to use an URL parser to first grab the path part to split with /. Then, you will have direct access to the slash-separated path parts that you may test against a very simple [0-9]{7} pattern and get them all with
def results = new URL(surl).path.split("/").findAll { it.matches(/\d{7}/) }
You may also take the first match:
def results = new URL(surl).path.split("/").findAll { it.matches(/\d{7}/) }.first()
Or last:
def results = new URL(surl).path.split("/").findAll { it.matches(/\d{7}/) }.last()
See the Groovy demo:
def surl = "https://stackoverflow.com/questions/6032324/problem-with-this-reg-expression"
def url = new URL(surl)
final result = url.path.split("/").findAll { it.matches(/\d{7}/) }.first()
print(result) // => 6032324

How can I validate dynamic tab and new line delimited string using regex?

I'm trying to implement a validation form with regex where I have to check whether a string is properly Tab and New Line delimited or not. I'm using jqBootstrapValidation. Column numbers can vary from 2 to 10. Like this image below:
What regex should I use?
I believe this is what you're looking for.
([A-Za-z0-9]+[\t\n])+[a-zA-Z0-9]+
This solution will work:
var s = "string here";
var regex = /\t/g;
var lines = s.split(/\n/).length - 1;
var valid = s.match(regex).length == 2 * lines;// valid or not.
alert(valid); // true or false.
Demo: http://jsfiddle.net/VP6Uj/2

Regex: Obtain ID(s) from URL

Getting my feet wet in Regular Expressions, and I'm having a difficult time getting this one to work.
I have a url as such:
/800-Flowers-inc-4124/18-roses-3123
Where 4124 is the business ID, and 3123 is the product ID.
The hard part for me is creating the capturing groups. Currently, my regex is as follows:
/(\d+)(?=/|$)/g
Unfortunately, that only selects the business ID, and doesn't return the product ID.
Any help is greatly appreciated, and if you provide a regex, I would love if you could put a little explanation
thanks!
Your regex is fine, except since you've used the / as the regex delimiter you need to escape it in the expression:
/(\d+)(?=\/|$)/g
Or, you can just use a different delimiter (e.g. #):
#(\d+)(?=/|$)#g
Depending on the language you're using it'll probably return the results in some sort of array, or there could be a 'findAll'-type method instead of just 'find'.
mathematical.coffee is correct:
var data = '/800-Flowers-inc-4124/18-roses-3123';
var myregexp = /(\d+)(?=\/|$)/g;
var match = myregexp.exec(data);
var result = "Matches:\n";
while (match != null) {
result += "match:" + match[0] + ',\n';
match = myregexp.exec(data);
}
alert(result);