regex to extract numbers starting from second symbol - javascript

Sorry for one more to the tons of regexp questions but I can't find anything similar to my needs. I want to output the string which can contain number or letter 'A' as the first symbol and numbers only on other positions. Input is any string, for example:
---INPUT--- -OUTPUT-
A123asdf456 -> A123456
0qw#$56-398 -> 056398
B12376B6f90 -> 12376690
12A12345BCt -> 1212345
What I tried is replace(/[^A\d]/g, '') (I use JS), which almost does the job except the case when there's A in the middle of the string. I tried to use ^ anchor but then the pattern doesn't match other numbers in the string. Not sure what is easier - extract matching characters or remove unmatching.

I think you can do it like this using a negative lookahead and then replace with an empty string.
In an non capturing group (?:, use a negative lookahad (?! to assert that what follows is not the beginning of the string followed by ^A or a digit \d. If that is the case, match any character .
(?:(?!^A|\d).)+
var pattern = /(?:(?!^A|\d).)+/g;
var strings = [
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
for (var i = 0; i < strings.length; i++) {
console.log(strings[i] + " ==> " + strings[i].replace(pattern, ""));
}

You can match and capture desired and undesired characters within two different sides of an alternation, then replace those undesired with nothing:
^(A)|\D
JS code:
var inputStrings = [
"A-123asdf456",
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
console.log(
inputStrings.map(v => v.replace(/^(A)|\D/g, "$1"))
);

You can use the following regex : /(^A)?\d+/g
var arr = ['A123asdf456','0qw#$56-398','B12376B6f90','12A12345BCt', 'A-123asdf456'],
result = arr.map(s => s.match(/(^A|\d)/g).join(''));
console.log(result);

Related

Regex match apostrophe inside, but not around words, inside a character set

I'm counting how many times different words appear in a text using Regular Expressions in JavaScript. My problem is when I have quoted words: 'word' should be counted simply as word (without the quotes, otherwise they'll behave as two different words), while it's should be counted as a whole word.
(?<=\w)(')(?=\w)
This regex can identify apostrophes inside, but not around words. Problem is, I can't use it inside a character set such as [\w]+.
(?<=\w)(')(?=\w)|[\w]+
Will count it's a 'miracle' of nature as 7 words, instead of 5 (it, ', s becoming 3 different words). Also, the third word should be selected simply as miracle, and not as 'miracle'.
To make things even more complicated, I need to capture diacritics too, so I'm using [A-Za-zÀ-ÖØ-öø-ÿ] instead of \w.
How can I accomplish that?
1) You can simply use /[^\s]+/g regex
const str = `it's a 'miracle' of nature`;
const result = str.match(/[^\s]+/g);
console.log(result.length);
console.log(result);
2) If you are calculating total number of words in a string then you can also use split as:
const str = `it's a 'miracle' of nature`;
const result = str.split(/\s+/);
console.log(result.length);
console.log(result);
3) If you want a word without quote at the starting and at the end then you can do as:
const str = `it's a 'miracle' of nature`;
const result = str.match(/[^\s]+/g).map((s) => {
s = s[0] === "'" ? s.slice(1) : s;
s = s[s.length - 1] === "'" ? s.slice(0, -1) : s;
return s;
});
console.log(result.length);
console.log(result);
You might use an alternation with 2 capture groups, and then check for the values of those groups.
(?<!\S)'(\S+)'(?!\S)|(\S+)
(?<!\S)' Negative lookbehind, assert a whitespace boundary to the left and match '
(\S+) Capture group 1, match 1+ non whitespace chars
'(?!\S) Match ' and assert a whitespace boundary to the right
| Or
(\S+) Capture group 2, match 1+ non whitespace chars
See a regex demo.
const regex = /(?<!\S)'(\S+)'(?!\S)|(\S+)/g;
const s = "it's a 'miracle' of nature";
Array.from(s.matchAll(regex), m => {
if (m[1]) console.log(m[1])
if (m[2]) console.log(m[2])
});

Replace after char '-' or '/' match

I'm trying to execute regex replace after match char, example 3674802/3 or 637884-ORG
The id can become one of them, in that case, how can I use regex replace to match to remove after the match?
Input var id = 3674802/3 or 637884-ORG;
Expected Output 3674802 or 637884
You could use sbustring method to take part of string only till '/' OR '-':
var input = "3674802/3";
var output = input.substr(0, input.indexOf('/'));
var input = "637884-ORG";
var output = input.substr(0, input.indexOf('-'));
var input = "3674802/3";
if (input.indexOf('/') > -1)
{
input = input.substr(0, input.indexOf('/'));
}
console.log(input);
var input = "637884-ORG";
if (input.indexOf('-') > -1)
{
input = input.substr(0, input.indexOf('-'));
}
console.log(input);
You can use a regex with a lookahead assertion
/(\d+)(?=[/-])/g
var id = "3674802/3"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
id = "637884-ORG"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
You don't need Regex for this. Regex is far more powerful than what you need.
You get away with the String's substring and indexOf methods.
indexOf takes in a character/substring and returns an integer. The integer represents what character position the character/substring starts at.
substring takes in a starting position and ending position, and returns the new string from the start to the end.
If are having trouble getting these to work; then, feel free to ask for more clarification.
You can use the following script:
var str = '3674802/3 or 637884-ORG';
var id = str.replace(/(\d+)[-\/](?:\d+|[A-Z]+)/g, '$1');
Details concerning the regex:
(\d+) - A seuence of digits, the 1st capturing group.
[-\/] - Either a minus or a slash. Because / are regex delimiters,
it must be escaped with a backslash.
(?: - Start of a non-capturing group, a "container" for alternatives.
\d+ - First alternative - a sequence of digits.
| - Alternative separator.
[A-Z]+ - Second alternative - a sequence of letters.
) - End of the non-capturing group.
g - global option.
The expression to replace with: $1 - replace the whole finding with
the first capturing group.
Thanks To everyone who responded to my question, was really helpful to resolve my issue.
Here is My answer that I built:
var str = ['8484683*ORG','7488575/2','647658-ORG'];
for(i=0;i<str.length;i++){
var regRep = /((\/\/[^\/]+)?\/.*)|(\-.*)|(\*.*)/;
var txt = str[i].replace(regRep,"");
console.log(txt);
}

Extract word between '=' and '('

I have the following string
234234=AWORDHERE('sdf.'aa')
where I need to extract AWORDHERE.
Sometimes there can be space in between.
234234= AWORDHERE('sdf.'aa')
Can I do this with a regular expression?
Or should I do it manually by finding indexes?
The datasets are huge, so it's important to do it as fast as possible.
Try this regex:
\d+=\s?(\w+)\(
Check Demo
in Javascript it would like that:
var myString = "234234=AWORDHERE('sdf.'aa')";// or 234234= AWORDHERE('sdf.'aa')
var myRegexp = /\d+=\s?(\w+)\(/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // AWORDHERE
You could do this at least three ways. You need to benchmark to see what's fastest.
Substring w/ indexes
function extract(from) {
var ixEq = from.indexOf("=");
var ixParen = from.indexOf("(");
return from.substring(ixEq + 1, ixParen);
}
.
Splits
function extract(from) {
var spEq = from.split("=");
var spParen = spEq[1].split("(");
return spParen[0];
}
Regex (demo)
Here is some sample regex you could use
/[^=]+=([^(]+).*/g
This says
[^=]+ - One or more character which is not an =
= - The = itself
( - creates a matching group so you can access your match in code
[^(]+ - One or more character which is not a (
) - closes the matching group
.* - Matches the rest of the line
the /g on the end tells it to perform the match on all lines.
Using look around you can search for string preceded by = and followed by ( as following.
Regex: (?<==)[A-Z ]+(?=\()
Explanation:
(?<==) checks if [A-Z ] is preceded by an =.
[A-Z ]+ matches your pattern.
(?=\() checks if matched pattern is followed by a (.
Regex101 Demo
var str = "234234= AWORDHERE('sdf.'aa')";
var regexp = /.*=\s+(\w+)\(.*\)/g;
var match = regexp.exec(str);
alert( match[1] );
I made my solution for this just a little more general than you asked for, but I don't think it takes much more time to execute. I didn't measure. If you need greater efficiency than this provides, comment and I or someone else can help you with that.
Here's what I did, using the command prompt of node:
> var s = "234234= AWORDHERE('sdf.'aa')"
undefined
> var a = s.match(/(\w+)=\s*(\w+)\s*\(.*/)
undefined
> a
[ '234234= AWORDHERE(\'sdf.\'aa\')',
'234234',
'AWORDHERE',
index: 0,
input: '234234= AWORDHERE(\'sdf.\'aa\')' ]
>
As you can see, this matches the number before the = in a[1], and it matches the AWORDHERE name as you requested in a[2]. This will work with any number (including zero) spaces before and/or after the =.

What's the exact regex to match the proper string?

My string has [1212,1212],[1212,11212],...
I'd like to extract each value into an array for example I'd want 1212,1212 as one pair and evaluate a series of steps.
Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. Basically I'm a noob in Regex, could someone please help.
Thanks in advance
You need some modifications for your regular expression for it to work correctly:
/\[[0-9]+,[0-9]+\]/g
You need to escape square brackets [ because they have special meaning.
[0-9] matches only one digits, you need the + quantifier to match one or more digits and thus [0-9]+.
Use the global modifier g to extract all matches.
Then you can extract all the values into an array like this:
var input = "[1212,1212],[1212,11212]";
var pattern = /\[[0-9]+,[0-9]+\]/g;
var result = [];
var currentMatch;
while((currentMatch = pattern.exec(input)) != null) {
result.push(currentMatch.toString());
}
result;
Or if you don't need to find the matches successively one at a time, then you can use String.match() as #Matthew Mcveigh did:
var input = "[1212,1212],[1212,11212]";
var result = input.match(/\[[0-9]+,[0-9]+\]/g);
It seems like you just need to match one or more digits before and after a comma, so you could do the following:
"[1212,1212],[1212,11212]".match(/\d+,\d+/g)
Which will give you the array: ["1212,1212", "1212,11212"]
To extract the pairs:
var result = "[1212,1212],[1212,11212]".match(/\d+,\d+/g);
for (var i = 0; i < result.length; i++) {
var pair = result[i].match(/\d+/g),
left = pair[0], right = pair[1];
alert("left: " + left + ", right: " + right);
}
You need to escape the literal brackets that you want to match. You can also use \d to match "any digit", which makes it tidier. Also, you're only matching one digit. You need to match "one or more" (+ quantifier)
/\[\d+,\d+\]/g
That g modifier finds all matches in the string, otherwise only the first one is found.

RegEx needed to split javascript string on "|" but not "\|"

We would like to split a string on instances of the pipe character |, but not if that character is preceded by an escape character, e.g. \|.
ex we would like to see the following string split into the following components
1|2|3\|4|5
1
2
3\|4
5
I'm expecting to be able to use the following javascript function, split, which takes a regular expression. What regex would I pass to split? We are cross platform and would like to support current and previous versions (1 version back) of IE, FF, and Chrome if possible.
Instead of a split, do a global match (the same way a lexical analyzer would):
match anything other than \\ or |
or match any escaped char
Something like this:
var str = "1|2|3\\|4|5";
var matches = str.match(/([^\\|]|\\.)+/g);
A quick explanation: ([^\\|]|\\.) matches either any character except '\' and '|' (pattern: [^\\|]) or (pattern: |) it matches any escaped character (pattern: \\.). The + after it tells it to match the previous once or more: the pattern ([^\\|]|\\.) will therefor be matches once or more. The g at the end of the regex literal tells the JavaScript regex engine to match the pattern globally instead of matching it just once.
What you're looking for is a "negative look-behind matching regular expression".
This isn't pretty, but it should split the list for you:
var output = input.replace(/(\\)?|/g, function($0,$1){ return $1?$1:$0+'\n';});
This will take your input string and replace all of the '|' characters NOT immediately preceded by a '\' character and replace them with '\n' characters.
A regex solution was posted as I was looking into this. So I just went ahead and wrote one without it. I did some simple benchmarks and it is -slightly- faster (I expected it to be slower...).
Without using Regex, if I understood what you desire, this should do the job:
function doSplit(input) {
var output = [];
var currPos = 0,
prevPos = -1;
while ((currPos = input.indexOf('|', currPos + 1)) != -1) {
if (input[currPos-1] == "\\") continue;
var recollect = input.substr(prevPos + 1, currPos - prevPos - 1);
prevPos = currPos;
output.push(recollect);
}
var recollect = input.substr(prevPos + 1);
output.push(recollect);
return output;
}
doSplit('1|2|3\\|4|5'); //returns [ '1', '2', '3\\|4', '5' ]

Categories

Resources