英文:
Replace Text in String
问题
我正在尝试编写一个正则表达式来替换字符串中特定的文本,其中文本的部分是可变的。
例如,以下是文本字符串示例:
XX 23080900012308091439
XX 23080900012308011439
XX 23080900012308231439
XX 23080900012308151439
对于以XX开头并以1439结尾的文本字符串,我想将1439替换为另一个4位数字(如1234)。
查找和替换后,输出将如下所示:
XX 23080900012308091440
XX 23080900012308011440
XX 23080900012308231440
XX 23080900012308151440
每次我尝试编写一个正则表达式来查找文本时,它都会给我所有的“1439”实例(不仅仅是以XX开头的文本字符串中的实例)。
- 有没有办法限制搜索范围只在以XX开头且以1439结尾的字符串中进行?
- 有没有办法仅在字符串以XX开头时进行替换?
已编辑以添加:
迄今为止已经有效的是:
查找:^(XX\s+)(\d{16})(.*)$
替换:$1$21440
https://regex101.com/r/dD0E4t/1
我认为我已经接近成功,但我无法让文本编辑器识别语法。
感谢您能提供的任何帮助!
英文:
I'm trying to write a RegEx expression to replace specific text in a string where parts of the text are variable.
For example, the text strings are the following:
XX 23080900012308091439
XX 23080900012308011439
XX 23080900012308231439
XX 23080900012308151439
For a text string that starts with XX and ends with 1439, I want to replace 1439 with another 4-digit number (like 1234).
After the find-and-replace, the output would be:
XX 23080900012308091440
XX 23080900012308011440
XX 23080900012308231440
XX 23080900012308151440
Each time I try to write a RegEx to find the text, it's giving me all instances of "1439" (not just ones in a text string that starts with XX).
- Is there a way to restrict the search to strings that start with XX and end with 1439?
- Is there a way to only make the replacement if the string starts with XX?
Edited to add:
This is what has worked so far:
Find: ^(XX\s+)(\d{16})(.*)$
Replace: $1$21440
https://regex101.com/r/dD0E4t/1
I think I'm getting close, but I can't get a text editor to recognize the syntax.
Thanks for any help you can provide!
答案1
得分: 1
如果您使用Notepad++(确保选择正则表达式),您可以使用一个捕获组:
^(XX\s+\d{16})1439$
解释
^
字符串的开头(XX\s+\d{16})
捕获组 1,匹配XX
后跟 1 个或多个空白字符和 16 个数字1439
$
字符串的结尾
(请注意,您也可以使用\h+
而不是\s+
来匹配一个或多个水平空白字符)
在替换中使用捕获组 1 的值,后跟 1440
,就像 \11440
一样。
或者您可以使用 \K
来忘记到目前为止匹配的内容,然后在替换中只使用 1440
。
^XX\s+\d{16}\K1439$
英文:
If you are using Notepad++ (make sure you select Regular expression), you use a single capture group:
^(XX\s+\d{16})1439$
Explanation
^
Start of string(XX\s+\d{16})
Capture group 1, matchXX
followed by 1+ whitespace chars and 16 digits1439
$
End of string
(note that you can also use \h+
instead of \s+
to match 1 or more horizontal whitespace chars)
In the replacement use the value of capture group 1 followed by 1440 like \11440
Or you can make use of \K
to forget what is matched so far, and use only 1440
in the replacement.
^XX\s+\d{16}\K1439$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论