Silly question, but I do not know how to find (2000) into a regular expression and replace it with [2000]
You can do:
str.replace(/\((\d+)\)/g, "[$1]");
Regex used: \((\d+)\)
( and ) are special char in regex
used for grouping, to match literal
( ), you need to escape them as
\( \)
\d is short for a digit. \d+
means one or more digits.
( ) is to group and remember the
number. The remembered number will
later be used in replacement.
g for global replacement. Mean
every occurrence of the patten in the
string will be replaced.
$1 is the number between (
)that was grouped and remembered.
/ / are the regex delimiters.
function _foo(str) {
return str.replace(/[(](\d*)[)]/, '[$1]');
}
alert( _foo("(2000)") ); // -> '[2000]'
alert( _foo("(30)") ); // -> '[30]'
alert( _foo("(abc)") ); // -> '(abc)'
alert( _foo("()") ); // -> '[]'
Like this: yourString.replace(/\(2000\)/, "[2000]");
Try this:
function foo(S) {
return S.replace(/\(([^\)]+)\)/g,"[$1]");
}
Related
This is the code I am using (but it only works for hyphens not for spaces)
console.log(
"some - text".replace(/\s\-/g, '').toLowerCase()
)
Can anyone point out what is wrong in this RegEx ?
The regex you have removes the space and the dash, leaving the second space
You need other regex to remove all spaces
console.log(
"some - text".replace(/\s\-/g, '') // space and dash
)
console.log(
"some - text".replace(/\s-\s/g, '') // space before and after a dash
)
console.log(
"some - text".replace(/\s+\-\s+/g, '') // any whitespace before and after
)
console.log(
"so- me - te-xt".replace(/\s|-/g, '') // all spaces and all dashes, can be written as a acharacter class [\s-]
)
Use\W for non-word character:
console.log("some - text".replace(/\W/g, '').toLowerCase())
Your regex is matching "(1 occurrence of some space)(definitely followed by 1 occurrence of ad ash)". You want it to match any occurrence of those, so use a character class in your regex (see: MDN WebDocs: JavaScript Character Classes, with brackets, /[\s\-]/g, like so:
console.log(
"some - text".replace(/[\s-]/g, '').toLowerCase()
)
Want to replace another character? Just throw it into the class and you're good to go.
This should pass the condition:
syntax_search = (){return 0;}
syntax_search = ( ) { fsf return 0;}
syntax_search = ( ) { return 0; }
syntax_search = (){ return; }
syntax_search = (){ if(x){ sdfsdf } return 0;}
syntax_search = (){ char x[20]; return };
It is not passing all the combinations above, What is the right way?
if( /^\s*(\s*)\s*{[\s\S]*\s+return\s*[0-9]*\s*;\s*}\s*/.test(syntax_search) )
You regular expression contains many unneeded complexities and there are some characters that need escaping such as { and }.
Anyway you can use this modified version of your regex and it should work.
^\s*\(\s*\)\s*\{(.*(return\s*\d*\s*;)\s*)\}\s*;?$
// ^
// |
// There was a ? here
Regex 101 Demo
Some issues:
As M42 pointed out, you need to escape the curly brackets
The parentheses at the begining also need to be escaped (otherwise you are defining a capture group)
"return" is required by the expression. Your first 2 test cases don't contain the word return and will fail. Is that on purpose?
Same as #3 for ;.
[\s\S]* Anything which is a space and everything which isn't. Replace by a dot .* If you need to also match a newline, use [^]*
This regex is not anchored to the end of the string so it will allow invalid strings. (You can put anything you want after the last }
/^\s*(\s*)\s*{[^]return\s\d*\s*;\s*}\s*$/
How can I retrieve the word my from between the two rounded brackets in the following sentence using a regex in JavaScript?
"This is (my) simple text"
console.log(
"This is (my) simple text".match(/\(([^)]+)\)/)[1]
);
\( being opening brace, ( — start of subexpression, [^)]+ — anything but closing parenthesis one or more times (you may want to replace + with *), ) — end of subexpression, \) — closing brace. The match() returns an array ["(my)","my"] from which the second element is extracted.
var txt = "This is (my) simple text";
re = /\((.*)\)/;
console.log(txt.match(re)[1]);
jsFiddle example
You may also try a non-regex method (of course if there are multiple such brackets, it will eventually need looping, or regex)
init = txt.indexOf('(');
fin = txt.indexOf(')');
console.log(txt.substr(init+1,fin-init-1))
For anyone looking to return multiple texts in multiple brackets
var testString = "(Charles) de (Gaulle), (Paris) [CDG]"
var reBrackets = /\((.*?)\)/g;
var listOfText = [];
var found;
while(found = reBrackets.exec(testString)) {
listOfText.push(found[1]);
};
Use this to get text between closest ( and ):
const string = "This is (my) (simple (text)"
console.log( string.match(/\(([^()]*)\)/)[1] )
console.log( string.match(/\(([^()]*)\)/g).map(function($0) { return $0.substring(1,$0.length-1) }) )
Results: my and ["my","text"].
EXPLANATION
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^()]* any character except: '(', ')' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\) ')'
to get fields from string formula.
var txt = "{{abctext/lsi)}} = {{abctext/lsi}} + {{adddddd}} / {{ttttttt}}";
re = /\{{(.*?)\}}/g;
console.log(txt.match(re));
to return multiple items within rounded brackets
var res2=str.split(/(|)/);
var items=res2.filter((ele,i)=>{
if(i%2!==0) {
return ele;
}
});
Is there any regex I can use to match blocks of exactly 10 digits? For instance, I have this:
/\d{10}(?!\d+)/g
And this matches 2154358383 when given 2154358383 fine, but is also matches 1213141516 when given 12345678910111213141516, which I don't want.
What I think I need is a look-behind assertion (in addition to my lookahead already in there), that checks to make sure the character preceding the match is not an integer, but I can't figure out how to do that.
I tried
/(?:[^\d]+)\d{10}(?!\d+)/g
But that broke my first match of 2154358383, which is bad.
How can I write this to only match groups of 10 integers (no more, no less) with unknown boundaries?
I should also note that I'm trying to extract these out of a much larger string, so ^ and $ are out of the question.
This should work: ([^\d]|^)\d{10}([^\d]|$)
Could you do something like:
([^\d]|^)(\d{10})([^\d]|$)
In other words, the beginning of the string or a non-digit, ten digits, then the end of the string or a non-digit. That should solve the cases you looked for above.
You can use the regex like this:
var regex = /([^\d]|^)(\d{10})([^\d]|$)/;
var match = regex.exec(s);
var digits = match[2];
This should match numbers at the beginning of the string (the ^) or in the middle/end (the [^\d] and the (?!\d). If you care about the exact match and not just that it matches in the first place, you'll need to grab the first group in the match.
/(?:[^\d]|^)(\d{10})(?!\d)/g
This would be easier if JavaScript regular expressions supported lookbehind.
What about the next?
perl -nle 'print if /(\b|\D)(\d{10})(\D|\b)/' <<EOF
123456789
x123456789
123456789x
1234567890
x1234567890
1234567890x
12345678901
x12345678901
x12345678901x
EOF
will print only
1234567890
x1234567890
1234567890x
I know you said "no ^" but maybe it's okay if you use it like this?:
rx = /(?:^|\D)(\d{10})(?!\d)/g
Here's a quick test:
> val = '1234567890 sdkjsdkjfsl 2234567890 323456789000 4234567890'
'1234567890 sdkjsdkjfsl 2234567890 323456789000 4234567890'
> rx.exec(val)[1]
'1234567890'
> rx.exec(val)[1]
'2234567890'
> rx.exec(val)[1]
'4234567890'
Try this
var re = /(?:^|[^\d])(\d{10})(?:$|[^\d])/g
re.exec ( "2154358383")
//["2154358383", "2154358383"]
re.exec ( "12345678910111213141516" )
//null
re.exec ( "abc1234567890def" )
//["c1234567890d", "1234567890"]
val = '1234567890 sdkjsdkjfsl 2234567890 323456789000 4234567890';
re.exec ( val )
//["1234567890 ", "1234567890"]
re.exec ( val )
//[" 2234567890 ", "2234567890"]
re.exec ( val )
//[" 4234567890", "4234567890"]
re.exec ( val )
//null
Simple with lookbehind:
/(?<!\d)\d{10}(?!\d)/g
i would cheat and do something like
if (myvar.toString().substring(1, 10) = "1234567890") ....
:)
I have the following javascript regex...
.replace("/^(a-zA-Z\-)/gi", '');
It isn't complete... in fact it's wrong. Essentially what I need to do is take a string like "XJ FC-X35 (1492)" and remove the () and it's contents and the whitespace before the parenthesis.
replace(/^(.*?)\s?\(([^)]+)\)$/gi, "$1$2")
Takes XJ FC-X35 (1492) and returns XJ FC-X351492.
Remove the $2 to turn XJ FC-X35 (1492) into XJ FC-X35, if that's what you wanted instead.
Long explanation
^ // From the start of the string
( // Capture a group ($1)
.*? // That contains 0 or more elements (non-greedy)
) // Finish group $1
\s? // Followed by 0 or 1 whitespace characters
\( // Followed by a "("
( // Capture a group ($2)
[ // That contains any characters in the following set
^) // Not a ")"
]+ // One or more times
) // Finish group $2
\)$ // Followed by a ")" followed by the end of the string.
Try this:
x = "XJ FC-X35 (1492)"
x.replace(/\s*\(.*?\)/,'');