https://regex101.com/r/sB9wW6/1
(?:(?<=\s)|^)@(\S+) <-- the problem in positive lookbehind
Working like this on prod: (?:\s|^)@(\S+), but I need a correct start index (without space).
Here is in JS:
var regex = new RegExp(/(?:(?<=\s)|^)@(\S+)/g);
Error parsing regular expression: Invalid regular expression: /(?:(?<=\s)|^)@(\S+)/
What am I doing wrong?
UPDATE
Ok, no lookbehind in JS :(
But anyways, I need a regex to get the proper start and end index of my match. Without leading space.
Solution 1
Make sure you always select the right regex engine at regex101.com. See an issue that occurred due to using a JS-only compatible regex with [^] construct in Python.
JS regex - at the time of answering this question - did not support lookbehinds. Now, it becomes more and more adopted after its introduction in ECMAScript 2018. You do not really need it here since you can use capturing groups:
The (?:\s|^)@(\S+) matches a whitespace or the start of string with (?:\s|^), then matches @, and then matches and captures into Group 1 one or more non-whitespace chars with (\S+).
To get the start/end indices, use
BONUS
My regex works at regex101.com, but not in...
First of all, have you checked the Code Generator link in the Tools pane on the left?
All languages - "Literal string" vs. "String literal" alert- Make sure you test against the same text used in code, literal string, at the regex tester. A common scenario is copy/pasting a string literal value directly into the test string field, with all string escape sequences like\n(line feed char),\r(carriage return),\t(tab char). See Regex_search c++, for example. Mind that they must be replaced with their literal counterparts. So, if you have in Pythontext = "Text\n\n abc", you must useText, two line breaks,abcin the regex tester text field.Text.*?abcwill never match it although you might think it "works". Yes,.does not always match line break chars, see How do I match any character across multiple lines in a regular expression?All languages - Backslash alert- Make sure you correctly use a backslash in your string literal, in most languages, in regular string literals, use double backslash, i.e.\dused at regex101.com must written as\\d. In raw string literals, use a single backslash, same as at regex101. Escaping word boundary is very important, since, in many languages (C#, Python, Java, JavaScript, Ruby, etc.),"\b"is used to define a BACKSPACE char, i.e. it is a valid string escape sequence. PHP does not support\bstring escape sequence, so"/\b/"='/\b/'there.All languages - Default flags - Global and Multiline- Note that by defaultmandgflags are enabled at regex101.com. So, if you use^and$, they will match at the start and end of lines correspondingly. If you need the same behavior in your code check how multiline mode is implemented and either use a specific flag, or - if supported - use an inline(?m)embedded (inline) modifier. Thegflag enables multiple occurrence matching, it is often implemented using specific functions/methods. Check your language reference to find the appropriate one.line-breaks - Line endings at regex101.com are LF only, you can't test strings with CRLF endings, see regex101.com VS myserver - different results. Solutions can be different for each regex library: either use
\R(PCRE, Java, Ruby) or some kind of\v(Boost, PCRE),\r?\n,(?:\r\n?|\n)/(?>\r\n?|\n)(good for .NET) or[\r\n]+in other libraries (see answers for C#, PHP).
Another issue related to the fact that you test your regex against a multiline string (not a list of standalone strings/lines) is that your patterns may consume the end of line,\n, char with negated character classes, see an issue like that.\Dmatched the end of line char, and in order to avoid it,[^\d\n]could be used, or other alternatives.php
- You are dealing with Unicode strings, or want shorthand character classes to match Unicode characters, too (e.g.\w+to matchСтрибижевorStribiżew, or\s+to match hard spaces), then you need to useumodifier, see preg_match() returns 0 although regex testers work
- To match all occurrences, usepreg_match_all, notpreg_matchwith/...pattern.../g, see PHP preg_match to find multiple occurrences and "Unknown modifier 'g' in..." when using preg_match in PHP?
- Your regex with inline backreference like\1refuses to work? Are you using a double quoted string literal? Use a single-quoted one, see Backreference does not work in PHPphplaravel
- Mind you need the regex delimiters around the pattern, see https://stackoverflow.com/questions/22430529python
- You usedre.matchthat only searches for a match at the start of the string, usere.search: Regex works fine on Pythex, but not in Python
- If the regex contains capturing group(s),re.findallreturns a list of captures/capture tuples. Either use non-capturing groups, orre.finditer, or remove redundant capturing groups, see re.findall behaves weird
- If you used^in the pattern to denote start of a line, not start of the whole string, or used$to denote the end of a line and not a string, passre.Morre.MULTILINEflag toremethod, see Using ^ to match beginning of line in Python regex
- If you try to match some text across multiple lines, and usere.DOTALLorre.S, or[\s\S]*/[\s\S]*?, and still nothing works, check if you read the file line by line, say, withfor line in file:. You must pass the whole file contents as the input to the regex method, see Getting Everything Between Two Characters Across New Lines.
- Having trouble adding flags to regex and trying something likepattern = r"/abc/gi"? See How to add modifers to regex in python?c#, .net
- .NET regex does not support possessive quantifiers like++,*+,??,{1,10}?, see .NET regex matching digits between optional text with possessive quantifer is not working
- When you match against a multiline string and useRegexOptions.Multilineoption (or inline(?m)modifier) with an$anchor in the pattern to match entire lines, and get no match in code, you need to add\r?before$, see .Net regex matching $ with the end of the string and not of line, even with multiline enabled
- To get multiple matches, useRegex.Matches, notRegex.Match, see RegEx Match multiple times in string
- Similar case as above: splitting a string into paragraphs, by a double line break sequence - C# / Regex Pattern works in online testing, but not at runtime
- You should remove regex delimiters, i.e.@"/\d+/"must actually look like@"\d+", see Simple and tested online regex containing regex delimiters does not work in C# code
- If you unnecessarily usedRegex.Escapeto escape all characters in a regular expression (likeRegex.Escape(@"\d+\.\d+")) you need to removeRegex.Escape, see Regular Expression working in regex tester, but not in c#dartflutter
- Use raw string literal,RegExp(r"\d"), or double backslashes (RegExp("\\d")) - https://stackoverflow.com/questions/59085824javascript
- Double escape backslashes in aRegExp("\\d"): Why do regex constructors need to be double escaped?
- (Negative) lookbehinds unsupported by most browsers: Regex works on browser but not in Node.js
- Strings are immutable, assign the.replaceresult to a var - The .replace() method does change the string in place
- Retrieve all matches withstr.match(/pat/g)- Regex101 and Js regex search showing different results or, withRegExp#exec, RegEx to extract all matches from string using RegExp.exec
- Replace all pattern matches in string: Why does javascript replace only first instance when using replace?javascriptangular
- Double the backslashes if you define a regex with a string literal, or just use a regex literal notation, see https://stackoverflow.com/questions/56097782java
- Word boundary not working? Make sure you use double backslashes,"\\b", see Regex \b word boundary not works
- Gettinginvalid escape sequenceexception? Same thing, double backslashes - Java doesn't work with regex \s, says: invalid escape sequence
-No match foundis bugging you? RunMatcher.find()/Matcher.matches()- Why does my regex work on RegexPlanet and regex101 but not in my code?
-.matches()requires a full string match, use.find(): Java Regex pattern that matches in any online tester but doesn't in Eclipse
- Access groups usingmatcher.group(x): Regex not working in Java while working otherwise
- Inside a character class, both[and]must be escaped - Using square brackets inside character class in Java regex
- You should not runmatcher.matches()andmatcher.find()consecutively, use onlyif (matcher.matches()) {...}to check if the pattern matches the whole string and then act accordingly, or useif (matcher.find())to check if there is a single match orwhile (matcher.find())to find multiple matches (orMatcher#results()). See Why does my regex work on RegexPlanet and regex101 but not in my code?scala
- Your regex attempts to match several lines, but you read the file line by line (e.g. usefor (line <- fSource.getLines))? Read it into a single variable (see matching new line in Scala regex, when reading from file)kotlin
- You haveRegex("/^\\d+$/")? Remove the outer slashes, they are regex delimiter chars that are not part of a pattern. See Find one or more word in string using Regex in Kotlin
- You expect a partial string match, but.matchEntirerequires a full string match? Use.find, see Regex doesn't match in Kotlinmongodb
- Do not enclose/.../with single/double quotation marks, see mongodb regex doesn't workc++
-regex_matchrequires a full string match, useregex_searchto find a partial match - Regex not working as expected with C++ regex_match
-regex_searchfinds the first match only. Usesregex_token_iteratororsregex_iteratorto get all matches: see What does std::match_results::size return?
- When you read a user-defined string usingstd::string input; std::cin >> input;, note thatcinwill only get to the first whitespace, to read the whole line properly, usestd::getline(std::cin, input);- C++ Regex to match '+' quantifier
-"\d"does not work, you need to use"\\d"orR"(\d)"(a raw string literal) - This regex doesn't work in c++
- Make sure the regex is tested against a literal text, not a string literal, see Regex_search c++go
- Double backslashes or use a raw string literal: Regular expression doesn't work in Go
- Go regex does not support lookarounds, select the right option (Go) at regex101.com before testing! Regex expression negated set not working golanggroovy
- Return all matches: Regex that works on regex101 does not work in Groovyr
- Double escape backslashes in the string literal: "'\w' is an unrecognized escape" in grep
- Useperl=TRUEto PCRE engine ((g)sub/(g)regexpr): Why is this regex using lookbehinds invalid in R?oracle
- Greediness of all quantifiers is set by the first quantifier in the regex, see Regex101 vs Oracle Regex (then, you need to make all the quantifiers as greedy as the first one)]
-\bdoes not work? Oracle regex does not support word boundaries at all, use workarounds as shown in Regex matching works on regex tester but not in oraclefirebase
- Double escape backslashes, make sure^only appears at the start of the pattern and$is located only at the end (if any), and note you cannot use more than 9 inline backreferences: Firebase Rules Regex Birthdayfirebasegoogle-cloud-firestore
- In Firestore security rules, the regular expression needs to be passed as a string, which also means it shouldn't be wrapped in/symbols, i.e. useallow create: if docId.matches("^\\d+$").... See https://stackoverflow.com/questions/63243300google-data-studio
-/pattern/ginREGEXP_REPLACEmust contain no/regex delimiters and flags (likeg) - see How to use Regex to replace square brackets from date field in Google Data Studio?google-sheets
- If you thinkREGEXEXTRACTdoes not return full matches, truncates the results, you should check if you have redundant capturing groups in your regex and remove them, or convert the capturing groups to non-capturing by add?:after the opening(, see Extract url domain root in Google Sheetsed
- Why does my regular expression work in X but not in Y?word-boundarypcrephp
-[[:<:]]and[[:>:]]do not work in the regex tester, although they are valid constructs in PCRE, see https://stackoverflow.com/questions/48670105snowflake-cloud-data-platform snowflake-sql - If you are writing a stored procedure, and
\\ddoes not work, you need to double them again and use\\\\d, see REGEX conversion of VARCHAR value to DATE in Snowflake stored procedure using RLIKE not consistent.
