【问题标题】:RegEx. How to remove blank space after a period before a punctuation character正则表达式。如何在标点符号之前的句点后删除空格
【发布时间】:2016-12-21 14:00:10
【问题描述】:

我有一个关于正则表达式的问题。假设我有这个字符串

"She gained about 55 pounds in...9 months. She was like an eating machine. ”Trump, a man who wants to be president: "

我想删除句号之后和字符之前的每个空格“并删除字符”

例如这部分句子

She was like an eating machine. ”Trump, a man who wants to be president: 

应该变成

She was like an eating machine.Trump, a man who wants to be president: "

谢谢大家,正则表达式不容易学。感谢任何帮助!再见 p.s 我正在使用软件 R,但我认为这无关紧要,因为正则表达式适用于每种编程语言

更新

我解决了我的问题,我想分享它,也许可以帮助其他人。我从 kaggle 下载了这个关于特朗普和希拉里推文的数据集。

在将数据导入 Knime(大学项目)之前,我必须做一些清理工作。 除了这个,我已经通过 gsub 解决了所有的编码问题。我终于设法用编码 UTF-8 在 R 中编写一个 csv 文件来解决它。显然我用相同的编码在 Knime 中读取了该文件

【问题讨论】:

  • 这可能会有所帮助:var str = '她就像一台进食机器。 "特朗普,一个想当总统的人:'str.replace(/\.\s"/g,".");
  • @Marco,我的回答对你有用吗?
  • 是的,抱歉,它也有效。我将您的答案标记为最有帮助的;)

标签: r regex


【解决方案1】:

如果您需要在点和双引号之间匹配任意数量的空格(1 个或多个),您可以使用

x <- "She gained about 55 pounds in...9 months. She was like an eating machine. ”Trump, a man who wants to be president: "
gsub("\\.\\s+”", ".", x)
## => [1] "She gained about 55 pounds in...9 months. She was like an eating machine.Trump, a man who wants to be president: "

\\. 匹配一个点,\\s+ 匹配一个或多个空格符号, 匹配一个

查看regex demoR demo

如果点和引号之间只有 1 个常规空格,则可以使用固定字符串替换:

gsub(". ”", ".", x, fixed=TRUE)

this R demo

【讨论】:

    【解决方案2】:

    这可能会有所帮助:

    var str = 'She was like an eating machine. "Trump, a man who wants to be president. "New value'; 
    str.replace(/\.\s"/g,".");
    

    【讨论】:

      【解决方案3】:

      http://regexr.com/ 是学习和测试正则表达式的好工具。

      我要添加到 Wiktor 的答案中的唯一一点是它与 "machine.”Trump" 不匹配。要匹配点之后和引号之前的任意数量的空格,请使用 * 量词:

      x <- "She gained about 55 pounds in...9 months. She was like an eating machine. ”Trump, a man who wants to be president: "
      gsub("\\.\\s*”", ".", x)
      

      【讨论】:

      • 请注意,OP 使用的是 R,而 regexr.com 仅支持 JS 正则表达式风格。例如,[.][^]*?" 可以在 regexr 中很好地工作,但不能在 R 中工作。R 基本 R 使用 TRE 正则表达式风格(我不知道一个好的在线正则表达式测试器)或 PCRE(与 perl=TRUE 一起使用时) ) - 那么regex101.com 是一个更好的选择。
      • 好点。 pcre 模式下的regex101.com 可能是学习 R 兼容正则表达式的更好选择。通过稍微修改并使用 perl 模式,您的 JS 示例可以在 R 中工作:
      • [.][^]*?" 等于 TRE [.].*?",或 PCRE 中的 (?s)[.].*?"
      • 或:gsub("[.][^*]*?”", ".", x, perl = TRUE)。抱歉耽搁了,打扰了。
      • 不,[^] 匹配任何字符,不是字符而是星号。无论如何,这已经是多余的了。
      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 2021-12-20
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多