开发者

Regular expression to replace this string

I have this string

"ABC-2341241244 | tb1 | value | tb2 | value | tb10 | value"

What can I do with regex to replace, for example 开发者_高级运维'| tb2 | value ' with '' with this,

"ABC-2341241244 | tb1 | value | tb10 | value"

I know the value tbxx is a variable that I have.

The Regex engine is javascript, not .Net or C#.


The exact syntax depends on the language you are using, but you need to escape the | character since it has special meaning inside regular expressions.

In perl you would do something like:

my $string = "ABC-2341241244 | tb1 | value | tb2 | value | tb10 | value";
$string =~ s/\| tb2 \| value //;

In java it would be:

String string = "ABC-2341241244 | tb1 | value | tb2 | value | tb10 | value";
string = string.replaceAll("\\| tb2 \\| value ", "");


You don't have enough information for a generic solution[1]. Is your string guaranteed to be regular?

It sounds like your data is well formed - you should parse it in some way:

Python:

import csv
input = "ABC-2341241244 | tb1 | value | tb2 | value | tb10 | value"
parts = input.split("|")
r = csv.reader([input],delimiter='|')
parts = r.next()
try:
  i = parts.index(" tb2 ")
  parts = parts[0:i] + parts[i+2:]
except ValueError:
  pass

print "|".join(parts)

prints:

ABC-2341241244 | tb1 | value | tb10 | value

[1] Is your delimiter '|'? Or is it ' | '? Can you escape | in your data? Are you only searching on tbXX identifiers?


javascript replace

var 
    deletePair = 'tb2',
    strIn = "ABC-2341241244 | tb1 | value | tb2 | toDeletevalue | tb10 | value",
    pattern = new RegExp("\\| " + deletePair + " \\| ([a-zA-Z0-9]+) ", "g"),
    result = strIn.replace(pattern, '');

document.write(result === "ABC-2341241244 | tb1 | value | tb10 | value" 
    ? 'ok'
    : 'failed'
);
document.write('<br />' + result);

edit

Added deletePair in which you specify what key in your key | val representation you want to delete

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜