Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
How can I get from string "C27_W112_V113_Table__6__1" string "6" or from string "C27_W120_V153_Table__22__1" string "22". thx
You can achieve it by two ways
Regex approach:
const re = /(\d+)__\d+$/;
let values = [
'C27_W112_V113_Table__6__1',
'C27_W120_V153_Table__22__1'
];
values.forEach(str => console.log(str.match(re)[1]));
string manipulation (I assume the value is always at the same place):
values.forEach(str => {
let reversed = str.split('').reverse().join('');
let index = reversed.indexOf('__');
console.log(reversed.slice(index+2, reversed.indexOf('__', index+1)));
});
Here a snippet
const re = /(\d+)__\d+$/;
let values = [
'C27_W112_V113_Table__6__1',
'C27_W120_V153_Table__22__1'
];
values.forEach(str => console.log(str.match(re)[1]));
console.log('--------');
values.forEach(str => {
let reversed = str.split('').reverse().join('');
let index = reversed.indexOf('__');
console.log(reversed.slice(index+2, reversed.indexOf('__', index+1)));
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've have a case where I'd need to do a case insensitive replacement of strings in a Go (json)string. The replacements can be of the following cases
Search string: SOME_SEARCH_STRING; Replacement String REPLACEMENT_STRING
Search string: "[\"SOME_SEARCH_STRING\"]"; Replacement String "[\"INTv2RPACS\"]"
I have the following as my regex
pattern := fmt.Sprintf(`(%s)`, searchString)
pat := regexp.MustCompile("(?i)" + pattern)
content = pat.ReplaceAllString(content, replacementString)
The above seems to work fine when the search and replacement string values are simple string, but it is failing when the search are replacement values arrays (ex. #2 above). What should be the regex updates that I need to do to be able to replaces arrays ?
Use regexp.QuoteMeta to quote meta characters in the search string.
pattern := fmt.Sprintf(`(%s)`, regexp.QuoteMeta(searchString))
pat := regexp.MustCompile("(?i)" + pattern)
content = pat.ReplaceAllString(content, replacementString)
package main
import (
"fmt"
"regexp"
)
type rep struct {
from string
to string
}
func replace(str string, reps []rep) (result string) {
result = str
for i := range reps {
rx := regexp.MustCompile(fmt.Sprintf("(?i)(%s)", regexp.QuoteMeta(reps[i].from)))
result = rx.ReplaceAllString(result, reps[i].to)
}
return
}
func main() {
content := `
{
"key_1": "SoME_SEArCH_STRING",
"key_2": "some_some_SEARCH_STRING_string",
"key_3": ["SOME_SEARCH_STRING"],
"key_4": "aBc"
}`
var replaces = []rep{
{`["SOME_SEARCH_STRING"]`, `["INTv2RPACS"]`},// important: array replacements before strings
{`SOME_SEARCH_STRING`, `REPLACEMENT_STRING`},
}
fmt.Println(content)
fmt.Println(replace(content, replaces))
}
output:
{
"key_1": "SoME_SEArCH_STRING",
"key_2": "some_some_SEARCH_STRING_string",
"key_3": ["SOME_SEARCH_STRING"],
"key_4": "aBc"
}
{
"key_1": "REPLACEMENT_STRING",
"key_2": "some_REPLACEMENT_STRING_string",
"key_3": ["INTv2RPACS"],
"key_4": "aBc"
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have following string
1,2,3,a,b,c,a,b,c,1,2,3,c,b,a,2,3,1,
I would like to get only the first occurrence of any number without changing the order. This would be
1,2,3,a,b,c,
With this regex (found # https://stackoverflow.com/a/29480898/9307482) I can find them, but only the last occurrences. And this reverses the order.
(\w)(?!.*?\1) (https://regex101.com/r/3fqpu9/1)
It doesn't matter if the regex ignores the comma. The order is important.
Regular expression is not meant for that purpose. You will need to use an index filter or Set on array of characters.
Since you don't have a language specified I assume you are using javascript.
Example modified from: https://stackoverflow.com/a/14438954/1456201
String.prototype.uniqueChars = function() {
return [...new Set(this)];
}
var unique = "1,2,3,a,b,c,a,b,c,1,2,3,c,b,a,2,3,1,".split(",").join('').uniqueChars();
console.log(unique); // Array(6) [ "1", "2", "3", "a", "b", "c" ]
I would use something like this:
// each index represents one digit: 0-9
const digits = new Array(10);
// make your string an array
const arr = '123abcabc123cba231'.split('');
// test for digit
var reg = new RegExp('^[0-9]$');
arr.forEach((val, index) => {
if (reg.test(val) && !reg.test(digits[val])) {
digits[val] = index;
}
});
console.log(`occurrences: ${digits}`); // [,0,1,2,,,,....]
To interpret, for the digits array, since you have nothing in the 0 index you know you have zero occurrences of zero. Since you have a zero in the 1 index, you know that your first one appears in the first character of your string (index zero for array). Two appears in index 1 and so on..
A perl way to do the job:
use Modern::Perl;
my $in = '4,d,e,1,2,3,4,a,b,c,d,e,f,a,b,c,1,2,3,c,b,a,2,3,1,';
my (%h, #r);
for (split',',$in) {
push #r, $_ unless exists $h{$_};
$h{$_} = 1;
}
say join',',#r;
Output:
4,d,e,1,2,3,a,b,c,f
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a string like this
"This is an example. Start color=BLUE and rest of the string"
I want to find "color=" coming after "Start" and replace "color=BLUE" with "color=None".
"color=BLUE" always comes after "Start". But "Start" can be anywhere in the entire string.
How I can do this using regex?
I would use pure, efficient string methods, this works even if there are multiple color after Start:
Dim s = "This is an example. Start color=BLUE and rest of color=Green the string"
Dim startIndex = s.IndexOf("Start", StringComparison.Ordinal)
If startIndex = -1 Then Return s ' or do whatever you want, there is no starting point
Dim colorIndex = s.IndexOf("color=", startIndex, StringComparison.Ordinal)
While colorIndex >= 0
colorIndex += "color=".Length
Dim endIndex = s.IndexOf(" ", colorIndex, StringComparison.Ordinal)
If endIndex = -1 Then Exit While
Dim oldColor = s.Substring(colorIndex, endIndex - colorIndex) ' just out of interest
Dim newColor = "None"
s = $"{s.Remove(colorIndex)}{newColor}{s.Substring(endIndex)}"
colorIndex = s.IndexOf("color=", endIndex, StringComparison.Ordinal)
End While
If you want to find also start or COLOR, so ignore the case, use for example s.IndexOf("color=", startIndex, StringComparison.OrdinalIgnoreCase).
An easy solution without regex :
MyString.Replace("color=Blue","color=None")
The Replace method replaces any portion of given string with the target string.
Hope this helps :)
This question already has answers here:
How to validate an e-mail address in swift?
(39 answers)
Closed 5 years ago.
I'm trying to make a regular expression that looks for an e-mail. Everything works . How to get a Bool variable that would mean whether such an expression was found or not?
let someString = "123milka#yandex.ru123"
let regexp = "([a-zA-Z]{1,20})#([a-zA-Z]{1,20}).(com|ru|org)"
if let range = someString.range(of: regexp, options: .regularExpression) {
let result : String = someString.substring(with: range)
print(result)
}
You already have an if test, so use that, setting your Boolean as you see fit. There are tons of ways of doing that, e.g.:
let success: Bool
if let range = someString.range(of: regexp, options: .regularExpression) {
success = true
let result = someString.substring(with: range)
print(result)
} else {
success = false
}