Issue with REGEX in javascript [duplicate] - regex

This question already has answers here:
How to tell if a string contains a certain character in JavaScript?
(21 answers)
Closed 4 years ago.
I get an issue using REGEX, it is probably about my REGEX but I need some helps.
I need to match all string containing "D"...
Test string 1 : D
Test string 2 : aaaaaaDqqqqq
Test string 3 : Dssssssss
Test string 4 : D4564646
Test string 5 : 1321313D2312
Test string 6 : ppppprrrrrr
My regex :
/^.+D.+|(:?^|\s)D$/gi
It works only for 1 and 2 and it should works for 1, 2, 3, 4 and 5.

In your case problem is with + operator which is literally Matches between one and unlimited times so it wont work if letter "D" will be in the beggining or the end of string. Try this regex: ^.*D.*$ with asterix, as it is defined as Matches between zero and unlimited times
See example

Following regex should work for you
.*D.*

If all you need to do is test for whether or not a string contains a D character, it's just /D/
var tests = [
"D",
"aaaaaaDqqqqq",
"Dssssssss",
"D4564646",
"1321313D2312",
"ppppprrrrrr"
]
tests.forEach(str => console.log(/D/.test(str)))

Instead of using a regex simply use the includes function
var string = "aaaaaaDqqqqq",
substring = "D";
if(string.includes(substring)){
console.log("contain")
}else{
console.log("don't contain")
}

Related

How to return/print matches on a string in RegEx in Flutter/Dart? [duplicate]

This question already has an answer here:
How to put all regex matches into a string list
(1 answer)
Closed 1 year ago.
I want to return a pattern through regEx in flutter every time it' found, I tested using the Regex operation it worked on the same string, returning the match after that included match 'text:' to '}' letters, but it does not print the matches in the flutter application.
The code I am using:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
print("allMatches : "+exp.allMatches(myString).toString());
The output print statement is printing I/flutter ( 5287): allMatches : (Instance of '_RegExpMatch', Instance of '_RegExpMatch')
instead of text: PM
Following is the screenshot of how it is parsing on regexr.com
Instead of using a non greedy match with a lookahead, I would suggest using a negated character class matching any char except } in capture group 1, and match the } after the group to prevent some backtracking.
\b(text:[^}]+)}
You can loop the result from allMatches and print group 1:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"\b(text:[^}]+)}");
for (var m in exp.allMatches(myString)) {
print(m[1]);
}
Output
text: PM
You need to use map method to retrieve the string from the matches:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
final matches = exp.allMatches(myString).map((m) => m.group(0)).toString();
print("allMatches : $matches");

Get the number between two characters - Typescript [duplicate]

This question already has answers here:
RegExp in TypeScript
(5 answers)
Closed 2 years ago.
I am new to Typescript and trying to make a webhook in my Google Cloud Functions.
I have a string: C1234567890A460450P10TS1596575969702
I want to use regex to extract the number 1234567890 from that string.
The first character C is fixed and does not change, the character A after the number is variable and can be any other alphabet.
The regex that matches the number is (?<=C)(\d{10})(?=\w).
I want to know how to execute this regex in Typescript so that I can get the number into a variable(eg: const number = [the number extracted from the string] //value 1234567890)
Edit 1:
Based on the provided suggestions (which I had tried already before posting this question), here is the code I could make out of it:
const string = request.body.string;
let regxp = new RegExp('(?<=C)(\d{10})(?=\w)');
const number = regxp.exec(string);
response.send(number);
This gives a blank response.
There is two problems, you never parsed the returned string to a number with parseInt and (?<=C) (positive lookbehind) is not always supported.
Second, your regular expression can be simplified into ^C\d{10} and a .splice(1) to remove the C.
const string: string = request.body.string;
const matches = s.match(/^C\d{10}/);
let number: number;
if(matches !== null) {
number = parseInt(matches[0].slice(1));
} else {
res.status(400).end(); // Assuming this is express
return;
}
res.send(number); // 1234567890
Playground

Java 8 Matcher says there are matches but groupCount is 0 [duplicate]

This question already has answers here:
Java RegEx Matcher.groupCount returns 0
(4 answers)
Closed 5 years ago.
Java 8 here. I have the following function:
public String extractArgs(String function) {
Pattern inRegex = Pattern.compile("in\\(.*\\)");
Matcher inMatch = inRegex.matcher(function);
log("num in(...) function matches: " + inMatch.groupCount() + "but does inMatch.matches()? " + inMatch.matches());
if(inMatch.groupCount() > 0) {
return inMatch.group(1);
} else {
return "";
}
}
When I pass it "in(hello)" as an argument, I get the following output:
num in(...) function matches: 0 but does inMatch.matches()? true
My understanding is that if inMatch.matches() returns true (which is happening), that I should have at least one match group (inMatch.groupCount > 0).
I'm trying to compare the inputted arg string against the regex and (if there is a match) obtain the blurb of text that is contained inside the "in(...) function". Hence if I call extractArgs("in(hello)") then it should return the string "hello". Where am I going awry?!
There is no capture groups in your original regex. To introduce a capture group (which you want), you should define the regular expression along the lines of:
in\\((.*)\\)
Note that I've added a () brackets around where the arguments supposed to go. This way I have created a capture group around .*, so you will now have the groups:
pattern.matcher("in(hello, World!)").group(1) // hello, World!

Regular expression exact part of letters match in middle of the word including Dot[.] [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 5 years ago.
I am looking for regular expression for exact letters in middle of word. which should match Dot(.) also.
Currently I am using regular expression is "\\w*."+inputString +"\\w*", "i" , actually period represents any letter in this expression.
eg:
inputData = {name:[abc.12, abcdef, bc1454, test, rahul, bc.reju, rewbc.]}
inputString = "bc."
var wordFormat = new RegExp('\\w*'+inputString +'\\w*', 'i');
workFormat.test(inputData);
scenario 1: Starting of word.
input : 'bc.'
actual output is: abc.12
expecting output is: abc.12, bc.reju, rewbc.
expect output should get only one because passing inputString matches only one item in array of object (inputData) so, expecting output item is 1.
Here is a demo - Regex101
You can modify this by replacing the "bc" with your search string.
\w*bc\w*\.\d*
updated Expression
\w*bc\.\d*
Here is the example that you can use as your requirement:
regular = "bc." //These was the actual input expression you want to test
var regularplacholder = '[character]';
var regularexpresion="/";
for(var index =0;index<regular.length;index++)
{
regularexpresion+=(regularplacholder.replace('character',regular[index]));
}
regularexpresion+='*'
if(regularexpresion.test('test string')){
//your logic here
}

Need a regex to capture numbered citations [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 5 years ago.
Bit of a regex newbie... sorry. I have a document with IEEE style citations, or numbers in brackets. They can be one number, as in [23], or several, as in [5, 7, 14], or a range, as in [12-15].
What I have now is [\[|\s|-]([0-9]{1,3})[\]|,|-].
This is capturing single numbers, and the first number in a group, but not subsequent numbers or either number in a range.
Then I need to refer to that number in an expression like \1.
I hope this is clear! I have a suspicion I don't understand the OR operator.
How about this?
(\[\d+\]|\[\d+-\d+\]|\[\d+(,\d+)*\])
Actually this can be even more siplified to : (\[\d+-\d+\]|\[\d+(,\d+)*\])
my #test = (
"[5,7,14]",
"[23]",
"[12-15]"
);
foreach my $val (#test) {
if ($val =~ /(\[\d+-\d+\]|\[\d+(,\d+)*\])/ ) {
print "match $val!\n";
}
else {
print "no match!\n";
}
}
This prints:
match [5,7,14]!
match [23]!
match [12-15]!
Whitespaces are not taken into account but you can add them if you need to
I think Jim's Answer is helpful, but some generalizing and coding for better understand:
If Questions was looking for more complex but possible one like [1,3-5]:
(\[\d+(,\s?\d+|\d*-\d+)*\])
^^^^ optional space after ','
//validates:
[3,33-24,7]
[3-34]
[1,3-5]
[1]
[1, 2]
Demo for this Regex
JavaScript code for replacing digits by links:
//define input string:
var mytext = "[3,33-24,7]\n[3-34]\n[1,3-5]\n[1]\n[1, 2]" ;
//call replace of matching [..] that calls digit replacing it-self
var newtext = mytext.replace(/(\[\d+(,\s?\d+|\d*-\d+)*\])/g ,
function(ci){ //ci is matched citations `[..]`
console.log(ci);
//so replace each number in `[..]` with custom links
return ci.replace(/\d+/g,
function(digit){
return ''+digit+'' ;
});
});
console.log(newtext);
/*output:
'[3,33-24,7]
[3-34]
[1,3-5]
[1]
[1, 2]'
*/